开发者

Order by IF EXISTS

开发者 https://www.devze.com 2022-12-11 19:57 出处:网络
Is there a way to order by column if it actually exists? ie: SELECT * ORDER BY IF(EXISTS(order_column), order_colu开发者_运维知识库mn ASC, name_column DESC)

Is there a way to order by column if it actually exists?

ie: SELECT * ORDER BY IF(EXISTS(order_column), order_colu开发者_运维知识库mn ASC, name_column DESC)

Thank you!


You could use ISNULL Instead

ORDER BY
    ISNULL(order_column, name_column)

Not sure how you'd add the DESC or ASC tho...


Here's my untested guess:

ORDER BY IF(ISNULL(order_column), "", order_column) ASC, name_column DESC

If order_column is NULL, an empty string will be substituted, which won't affect the sort. If it's not NULL, it will be sorted before the name column.

If Mysql won't let you use an expression in the ORDER BY, you can always create an "artificial" column in the SELECT:

SELECT 
  IF (ISNULL(order_column), "     ", order_column) 
     AS my_order_column, 
  name_column 
FROM table 
ORDER BY my_order_column ASC, name_column DESC.


No, EXISTS must only be used with a subquery and in the WHERE clause. May you be more specific? What do you mean by 'existing column'?


The best way to do this is create an expression that evaluate the if exists as part of the select query. You can have the expression return order_column or name_column

implemention depends on the SQL you are using, but here you can normallly us IIf(...) but you may need to check for null

0

精彩评论

暂无评论...
验证码 换一张
取 消