SQL - order by语句

5

I've got tables like:

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语句获取所有用户,就像将第一个ORDER BY语句限制为只影响第一行一样...


1
如果您已经得到了问题的答案,请接受它。 - Michael Riley - AKA Gunny
3个回答

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不为空进行排序——mysql会将此布尔结果强制转换为整数1或0,可以进行排序。因此,降序排序使所有值为1的(非空B.members)首先排序。


几乎搞定了: ORDER BY (tableb.year IS NULL) ASC,(tableb.member IS NOT NULL) DESC。已经接近正确,现在的问题是我想先获取B.catA,然后是B.catB。如果可能的话,我只想获取catA和catB中最新的,之后顺序无关紧要... - joxxe
已修复: ORDER BY(CASE tableB.year WHEN EXTRACT(YEAR FROM now()) THEN 0 ELSE 1 END) ASC,tableA.id desc; - joxxe

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

0
无论您的选择有多么复杂,您总是可以使用“order by”来排序。只需将数据收集元素放入派生表中,从中进行选择,并按结果排序即可。类似于...
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 值。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接