【问题标题】:SQL - order by statementSQL - 按语句排序
【发布时间】:2011-10-28 19:40:07
【问题描述】:

我有如下表格:

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 statement 来获得它们吗?就像限制一阶语句只影响第一行...

【问题讨论】:

  • 如果您的问题有答案,请接受。

标签: mysql sql postgresql sql-order-by


【解决方案1】:

这样的?

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(不是 null B.members)首先排序。

【讨论】:

  • 几乎明白了:ORDER BY (tableb.year IS NULL) ASC,(tableb.member IS NOT NULL) DESC。完全正确,现在的问题是我想先获得 B.catA,然后是 B.catB。如果可能的话,我只想要最新的 catA 和 catB,之后顺序无关紧要......
  • 修复它:ORDER BY(CASE tableB.year WHEN EXTRACT(YEAR FROM now()) THEN 0 ELSE 1 END) ASC,tableA.id desc;
【解决方案2】:

根据您的排序规则:

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

【讨论】:

    【解决方案3】:

    您始终可以“排序”,无论您的选择多么复杂,都可以将数据收集元素放入派生表中,从中进行选择,然后按结果排序。比如……

    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 值。

    【讨论】:

      猜你喜欢
      • 2012-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-21
      • 2012-06-11
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      相关资源
      最近更新 更多