MySQL查询 - 排序和分组的混合

时间:2016-04-11 15:15:05

标签: mysql sql sorting grouping

我正试图从表格中获取以下信息:

  • 按" b"排序(表A升序,表B降序)
  • 所有" u"首先显示特定值(在此示例中为u = 3) - 然后顺序不重要
  • N(NULL)总是在最后
  • no" r"可能会发生两次(但所有不同的" r"必须存在)

使用" ORDER BY IFNULL(u,99999999)!= 3,u,b"标准1,2和3有效,但最后,我没有任何线索。

使用DISTINCT,我无法达到目标,就像使用GROUP BY一样。

有没有人有想法? 非常感谢提前。

start table          target table A 
+----------------+   +----------------+
| id | r | u | b |   | id | r | u | b |
+----------------+   +----------------+
|  1 | 1 | 1 | 9 |   | 18 | 5 | 3 | 1 |
|  2 | 1 | 3 | 4 |   | 2  | 1 | 3 | 4 |
|  3 | 1 | 4 | 6 |   | 15 | 4 | 3 | 7 |
|  4 | 1 | 5 | 5 |   | 11 | 3 | 3 | 8 |
|  5 | 2 | 1 | 2 |   | *  | 2 | * | * |
|  6 | 2 | 2 | 1 |   | 21 | 6 | N | N |
|  7 | 2 | 4 | 5 |   +----------------+
|  8 | 2 | 5 | 7 |
|  9 | 3 | 1 | 4 |
| 10 | 3 | 2 | 3 |
| 11 | 3 | 3 | 8 |
| 12 | 3 | 5 | 2 |   target table B
| 13 | 4 | 1 | 3 |   +----------------+
| 14 | 4 | 2 | 2 |   | id | r | u | b |
| 15 | 4 | 3 | 7 |   +----------------+
| 16 | 4 | 4 | 6 |   | 11 | 3 | 3 | 8 |
| 17 | 5 | 2 | 9 |   | 15 | 4 | 3 | 7 |
| 18 | 5 | 3 | 1 |   | 2  | 1 | 3 | 4 |
| 19 | 5 | 4 | 6 |   | 18 | 5 | 3 | 1 |
| 20 | 5 | 5 | 4 |   | *  | 2 | * | * |
| 21 | 6 | N | N |   | 21 | 6 | N | N |
+----------------+   +----------------+

1 个答案:

答案 0 :(得分:2)

SELECT  *
FROM    mytable m
WHERE   id =
        (
        SELECT  id
        FROM    mytable mi
        WHERE   mi.r = m.r
        ORDER BY
                u IS NULL, u = 3 DESC, b, id
        LIMIT 1
        )
ORDER BY
        u IS NULL, u = 3 DESC, b

更新

SELECT  *
FROM    objects o
LEFT JOIN
        ratings r
ON      r.id = COALESCE(
        (
        SELECT  id
        FROM    ratings
        WHERE   object_id = o.id
                AND user_id = :myuser
        ORDER BY
                rating DESC
        LIMIT   1
        ),
        (
        SELECT  id
        FROM    ratings
        WHERE   object_id = o.id
        ORDER BY
                rating DESC
        LIMIT   1
        )
        )