简体   繁体   English

mysql-基于空值和空值的排序列表

[英]mysql- sort list based on empty and null values as last in column

I have a table of users with basic details id, their names and profile photo (link to photo, actually) 我有一张包含基本详细信息ID,他们的姓名和个人资料照片的用户表(实际上是照片的链接)

CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL,
  `userName` varchar(60) NOT NULL,
  `photo` varchar(50) NULL,
  `status` int(11) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=42 DEFAULT CHARSET=latin1;

INSERT INTO `users` (`id`, `userName`,`photo`, `status`) VALUES
(1, 'John', 'john.png',1),
(2, 'Jane', 'jane.png',1),
(3, 'Ali', '',1),

(6, 'Bruce', 'bruce.png',1),

(7, 'Martha', '',1),
(8, 'Sidney', '',1),
(10, 'Charlie', 'charlie.png',1),

(12, 'Elisa', '',1),
(14, 'Samantha', 'samantha.png',1),
(15, 'Hannah', 'hannah.png',1),

(16, 'Hannah', '',1),
(17, 'Kevin', 'kevin1.png',1),
(18, 'Kevin', 'kevin2.png',1),
(19, 'Ruth', '',1);

Not all users have profile picture. 并非所有用户都有个人资料图片。 I would like to list these users in alphabetic order and also show users who have profile picture in front. 我想按字母顺序列出这些用户,并显示前面有头像的用户。

This is the query that I wrote: 这是我写的查询:

select * from users ORDER BY photo DESC ;

It sorts users based on photo value but they are not being shown in alphabetic order. 它根据照片值对用户进行排序,但不会按字母顺序显示用户。

Is it possible to list these users such that all users who have photos will appear top on the list with [userName] in alphabetic order? 是否可以列出这些用户,以便所有有照片的用户以[userName]的字母顺序出现在列表的顶部?

SQL FIDDLE SQL字段

''更改为NULL后...

SELECT * FROM users ORDER BY photo IS NULL,username;

You have empty vlaues here. 您在这里有空洞。 So you can use this way. 因此,您可以使用这种方式。

SELECT * FROM users ORDER BY if(photo = '' or photo is null,1,0), userName

But in mysql has a method to order null values with (-). 但是在mysql中有一种用(-)排序空值的方法。

SELECT * FROM users ORDER BY -photo DESC, userName ASC

Here photo column data order as null values last because of DESC order 在此,由于DESC顺序,照片列数据的顺序为空值的情况持续存在

OR 要么

SELECT * FROM users ORDER BY
CASE WHEN photo IS NULL THEN 1 ELSE 0 END ASC, userName ASC

If you want 1st people without picture and then other (while sorting these 2 groups alphabetically): 如果您想要第一个没有图片的人然后另一个(在按字母顺序对这两个组进行排序时):

select * from users ORDER BY photo,userName ASC ;

Waiting your feed back if it is not exactly what you want. 如果反馈不完全符合您的要求,请稍候。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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