加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MySql教程 > 正文

mysql – SQL – 按语句排序

发布时间:2020-12-11 23:49:00 所属栏目:MySql教程 来源:网络整理
导读:我有这样的表: table Aid name email1 test1 ex@ex.com2 test2 ex@ex.com3 test3 ex@ex.com4 test4 ....5 test5 ....table Bid catA catB year member 1 false true 2011 22 true false 2011 33 fals true 2010 5 我想获得表A中的每一行并按以下方式对其进

我有这样的表:

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

我想获得表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.

我知道我可以拥有特定的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

首先按表B中的年份字段对所有结果进行排序,这将获得2011年,2010年等等…表B中未列出的任何成员将具有空年份并排序到列表的底部.接下来排序由B.member不为null – mysql将此布尔结果强制转换为整数1或0,可以对其进行排序,因此按降序排序以使所有1(非空B.members)排序优先.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读