Trying to order the column name is not null as first, if the first column is null but not second column is not null etc..
Table :
id name1 name2 name3
1. a b
2. a1 c
3. b1 c1
4. c2
5. c3
6. a2
7. b2 c4
8. a3
Expected result
id
1
2
6
8
3
7
4
5
I have tried to use COALESCE AND IFNULL But it's return zero result.
As documented under COALESCE( value ,...)
:
Returns the first non-
NULL
value in the list, orNULL
if there are no non-NULL
values.mysql> SELECT COALESCE(NULL,1); -> 1 mysql> SELECT COALESCE(NULL,NULL,NULL); -> NULL
As documented under IS NULL
:
Tests whether a value is
NULL
.mysql> SELECT 1 IS NULL, 0 IS NULL, NULL IS NULL; -> 0, 0, 1
Therefore:
SELECT id
FROM Table1
ORDER BY COALESCE(name1, name2, name3) IS NULL,
COALESCE(name1, name2, name3)
See it on sqlfiddle .
This sorts first on whether all three columns are NULL
(those that are will have an IS NULL
result of one, which will come after those that aren't with a result of zero); then by the actual value of the first non- NULL
column.
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.