jox*_*xxe 5 mysql sql postgresql sql-order-by
我有这样的表:
table A
id name email
1 test1 ex@ex.com
2 test2 ex@ex.com
3 test3 ex@ex.com
4 test4 ....
5 test5 ....
table B
id catA catB year member
1 false true 2011 2
2 true false 2011 3
3 fals true 2010 5
Run Code Online (Sandbox Code Playgroud)
我想获得表A中的每一行并按以下方式对其进行排序:
FIRST, get user 2 (current year, based on table B)
SECOND, get user 3 (current year, based on table B)
after that get users that is in table B
after that get all other users.
Run Code Online (Sandbox Code Playgroud)
我知道我可以拥有特定的sql来获取前两个用户,而其余的用户.但是,我不能用一个很好的ORDER by语句来获取它们吗?像限制第一顺序语句只是影响第一行...
像这样的东西吗?
select A.id, A.name, A.email, B.catA, B.catB, B.year
from A
join B on A.id = B.member
ORDER BY B.year DESC, (B.member IS NOT NULL) DESC
Run Code Online (Sandbox Code Playgroud)
首先按表 B 中的年份字段对所有结果进行排序,这会得到 2011 年、2010 年等...表 B 中未列出的任何成员都将具有空年份并排序到列表底部。接下来按 B.member 不为空进行排序 - mysql 会将这个布尔结果强制转换为可以排序的整数 1 或 0,因此降序排序以使所有 1(不为空的 B.members)首先排序。
| 归档时间: |
|
| 查看次数: |
160 次 |
| 最近记录: |