我正试图从表格中获取以下信息:
使用" 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 |
+----------------+ +----------------+
答案 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
)
)