我想获取用户的记录,我希望得到10个用户,而不是用户有status = 1的用户首先显示它,如果两个用户的名字以相同的字母开头,它将按姓名显示asc用户状态= 1,用户状态应为0或1. 按名称排序只有那些状态= 1的用户
这是我的查询
SELECT users_id, concat(users_fname, ' ', users_lname) as name,
IFNULL(users.users_age, '') as users_age
FROM `users` ORDER BY status DESC, name ASC LIMIT 10
提前致谢,请帮我简短说明。
答案 0 :(得分:3)
希望它会帮助你
ORDER BY status DESC, (CASE WHEN status = '1' THEN 1 ELSE 0 END),name ASC
这是整个查询
SELECT users_id, concat(users_fname, ' ', users_lname) as name,
IFNULL(users.users_age, '') as users_age
FROM `users` ORDER BY status DESC, (CASE WHEN status = '1' THEN 1 ELSE 0 END),name ASC LIMIT 10
答案 1 :(得分:0)
在RAND
子句中使用ORDER BY
的结果是,无论用户status
如何,都会随机订购用户。
您必须在子查询中选择10个随机记录,然后在外部查询中使用此集合,根据需要按status
排序:
SELECT users_id, name, users_age
FROM
(
SELECT users_id, concat(users_fname, ' ', users_lname) as name,
IFNULL(users.users_age, '') as users_age
FROM `users`
ORDER BY RAND() LIMIT 10
) AS t
ORDER BY status DESC,
CASE
WHEN status = 1 THEN name
ELSE 1
END ASC