0

In MySQL I want to sort by a field if that field exists as a column in the table. If that field does not exist I want the query to ignore that segment of the query. If I try something like

SELECT
    post.*
FROM post AS post
WHERE post.postid IN (9818,9814,9815)
ORDER BY IFNULL(post.vote_count,0) > 5 DESC;

at the end of my query I get the error:

#1054 - Unknown column 'post.vote_count' in 'order clause'

The table structure for post has postid, threadid, and title fields. How should I write this query?

(I've seen Ordering by a field, only if it exists. That answer doesn't work for me since I can't add the earlier portion of the query, "IFNULL(post.vote_count,0) as newvotecount".)

Community
  • 1
  • 1
zylstra
  • 740
  • 1
  • 8
  • 22

2 Answers2

-2

You can not use field in query if it is not exists in table (or as alias in query)

Volk
  • 46
  • 4
-2

In Oracle u can do this by using following

    SELECT * FROM table_name
    ORDER BY CASE WHEN EXISTS (select 1
                              FROM ALL_TAB_COLUMNS 
                              WHERE lower(column_name) IN lower('column1_name') AND lower(table_name) = lower('table_name')) THEN column1_name
                   ELSE column2_name
                   END;

Same way u replace the Oracle System table with Mysql System Table


For Mysql :

    SELECT DISTINCT TABLE_NAME 
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE COLUMN_NAME IN ('columnA','ColumnB')

    AND TABLE_SCHEMA='YourDatabase';

Ref

Community
  • 1
  • 1