我有这样的表:
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语句来获取它们吗?就像限制第一顺序语句只影响第一行......
答案 0 :(得分:4)
这样的东西?
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)排序。
答案 1 :(得分:0)
根据您的排序规则:
after that get users that is in table B
after that get all other users.
我假设表A中有一些用户在B中不存在,所以你想要使用LEFT JOIN。
SELECT a.id, a.name, a.email
FROM a
LEFT JOIN b
ON a.id = b.member
ORDER BY ISNULL(b.year), b.year DESC, a.name
答案 2 :(得分:0)
您可以随时“排序”,但是您的选择非常复杂,请将数据收集元素放入派生表中,从中进行选择,然后按结果排序。有点像...
SELECT col1,
col2,
col3
FROM
(SELECT 1 as col1,
col2,
' ' AS col3
FROM blah...blah...blah
UNION
SELECT 2 AS col1
col2,
col3
FROM blah...blah...blah
UNION
and so on) myderivedtable
ORDER BY col1,
col2,
col3
您只需确保在每个查询中选择的所有列都相同,否则应处理NULL值。