当前表事件:
| eventId | personId | type | title | score |
+-----------+------------+--------+---------+---------+
| 1 | 1 | movie | Mission | 12 |
| 2 | 1 | movie | UNCLE | 32 |
| 3 | 1 | show | U2 | 17 |
| 4 | 1 | show | Leroy | 13 |
| 5 | 2 | movie | Holmes | 19 |
| 6 | 2 | movie | Compton | 14 |
| 7 | 2 | show | Imagine | 22 |
| 8 | 2 | show | Kane | 22 |
MySQL示例:
SELECT @personId:=personId as personId,
(
SELECT title FROM Events
WHERE rate = (SELECT MAX(score) FROM Events)
AND type = ‘movie’ AND personId=@personId
) as movie,
(
SELECT title FROM Events
WHERE rate = (SELECT MAX(score) FROM Events)
AND type = ‘movie’ AND personId=@personId
) as show,
FROM Events
GROUP BY personId
ORDER BY personId;
期望的输出:
| personId | movie | show |
+------------+----------+---------+
| 1 | UNCLE | U2 |
| 2 | Holmes | Imagine |
所需的结果是在“事件”表中显示电影的MAX()分数和每人的显示。我的实际输出包含NULLS并需要很长时间才能加载。我的实际事件表有大约20,000个条目。
UPDATE解决方案(从前两个答案派生以提高性能)
SELECT e.personId,
(
SELECT o.title
FROM Events o
LEFT JOIN Events b
ON o.personId = b.personId AND o.score < b.score
AND o.type = b.type
WHERE o.type = 'movie' AND o.personId=e.personId LIMIT 1
) as best_movie ,
(
SELECT o.title
FROM Events o
LEFT JOIN Events b
ON o.personId = b.personId AND o.score < b.score
AND o.type = b.type
WHERE o.type = 'show' AND o.personId=e.personId LIMIT 1
) as best_show
FROM Events e
GROUP BY e.personId
ORDER BY e.personId
答案 0 :(得分:0)
我不确定这是否正是你所需要的。
但我只是猜测,可能你不需要多列?
http://sqlfiddle.com/#!9/04b27/4
SELECT e.*
FROM `events` e
left join `events` e1
on e.type = e1.type
and e.score<e1.score
WHERE e1.eventId IS NULL
GROUP BY personId, type, score
更新如果您需要每人最高分数+类型,您可以
http://sqlfiddle.com/#!9/04b27/13
SELECT e.*
FROM `events` e
left join `events` e1
on e.personId = e1.personId
and e.type = e1.type
and e.score<e1.score
WHERE e1.eventId IS NULL
GROUP BY personId, score