gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:19:56 25 4
gpt4 key购买 nike

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

  • 按“b”排序(表 A 升序,表 B 降序)
  • 所有具有特定值的“u”首先出现(在此示例中 u=3) - 那么顺序并不重要
  • N (NULL) 始终位于末尾
  • “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 |
+----------------+ +----------------+

最佳答案

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
)
)

关于MySQL 查询 - 排序和分组的混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36552675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com