如何使用空列值对mysql表进行排序

时间:2014-04-23 12:57:11

标签: mysql mysqli

我有一个包含以下架构的表。我需要按对表进行排序,如果存在 img_link 的行(不是 null ),则首先进行排序。只需要做的是 - 按 int列排序,然后按 varchar column 排序。

+-----+--------+-----------+-----------+
| id  | name   | img_link  |  points   |
+-----+--------+-----------+-----------+
| 11  | smpl   | path.jpg  |  10       |
+-----+--------+-----------+-----------+
| 12  | main   |  null     |  20       |
+-----+--------+-----------+-----------+
| 13  | abcd   |  null     |  10       |
+-----+--------+-----------+-----------+
| 14  | xyls   | img_.png  |  10       |
+-----+--------+-----------+-----------+

需要像

这样的结果
+-----+
| id  |
+-----+
| 12  |
+-----+
| 11  |
+-----+
| 14  |
+-----+
| 13  |
+-----+

提前致谢..

5 个答案:

答案 0 :(得分:2)

试试这个

SELECT * FROM table_name ORDER BY points DESC ,ISNULL(img_link), img_link 

答案 1 :(得分:1)

你基本上用文字写出了你需要做的事情。

SELECT id FROM someTable ORDER BY points DESC, img_link DESC;

DEMO

答案 2 :(得分:1)

另一种方式是

select *
from table
order by `points` desc,
if(img_link = '' or img_link is null,1,0)

<强> DEMO

答案 3 :(得分:0)

试试这个:

select * from tabalename where img_link is not null order by point desc union select * from tabalename where img_link is null order by point desc

答案 4 :(得分:0)

SELECT * FROM my_table ORDER BY points DESC, img_link IS NULL, img_link DESC;