简体   繁体   中英

Mysql order by column when not empty then order by other column

I wouls like some help that has had me stumpted for two days. I need to retirieve data from a database and order it by column1 when it isn't empty and then the rest of the result by column2

column1      column2
1            11
2            12
3            13
             14
             15
             16

Required result

1,2,3,14,15,16

I've tried numerous approaches, my latest failed attempt being

$SQL = "SELECT * FROM table ORDER BY COALESCE(column1,column2) DESC";

and

`$SQL = "SELECT * FROM table ORDER BY COALESCE(column1,column2) ASC";

My above SQL is returning NULL value column1 above column2

This should work:

$SQL = "SELECT * FROM table ORDER BY COALESCE(NULLIF(Other,''), column2) DESC";

I saw it here: SQL Coalesce with empty string

coalesce() would only work if the "empty" values in column1 are actually NULL . Empty strings will not trigger a coalesce() operation.

Beyond that, your query will NOT work. You cannot do a select * with two columns and somehow magically get one single column in the result. For this you'll need a UNION query:

(SELECT column1 AS col FROM yourtable)

UNION ALL

(SELECT column2 AS col FROM yourtable)
ORDER BY col

老问题,但这个解决方案对我有用:

$SQL = "SELECT * FROM table ORDER BY COALESCE(NULLIF(column1, ''), column2)";

You should be able to use CASE like so:

SELECT *
FROM table
ORDER BY 
CASE WHEN LENGTH(column1) IS >0 THEN column1 
ELSE column2 END 
ASC

http://dev.mysql.com/doc/refman/5.0/en/case.html

If you want 1 column, you could try a combination of NULLIF and COALESCE , that should account for both empty and null values

SELECT COALESCE(NULLIF(column1, ''), column2) AS COL
FROM table

SQLFiddle Demo

In case you actually want all of the numbers on a single result row, separated by commas, you can use GROUP_CONCAT along with the previous code:

SELECT GROUP_CONCAT(COALESCE(NULLIF(column1, ''), column2)) AS col
FROM table

SQLFiddle Demo2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM