在where条件中使用Count()运算符时,我得到了Error Code 1111. Invalid use of group function
。我认为问题在于不允许在WHERE子句中使用count运算符,但是我不确定如何使行的计数成为可用状态。
查询的目的是选择主题已观看多部电影的字段。诀窍是subject_id是带有movie_id的复合键。我在过滤主题仅看过一部电影的行时遇到问题。
查询:
SELECT
measures.Subject_id,
measures.Movie_id,
measures.Median_heart_rate AS Variation
FROM measures
WHERE COUNT(measures.Subject_id) > 1;
结果:
Subject_id Movie_id Variation
001 1 45
001 35 15
002 42 2
003 1 4
003 2 5
预期结果:
Subject_id Movie_id Variation
001 1 45
001 35 15
003 1 4
003 2 5
答案 0 :(得分:1)
COUNT应该在SELECT子句中,而不在WHERE子句中。
要过滤不重复的subject_id行,可以使用带有COUNT的内部查询:
SELECT `subject_id`,
`movie_id`,
`median_heart_rate` AS Variation
FROM `measures` m1
WHERE (SELECT Count(1)
FROM `measures` m2
WHERE m2.`subject_id` = m1.`subject_id`) > 1;
答案 1 :(得分:0)
在MySQL 8.0中,您可以使用窗口函数COUNT(...) OVER(...)
来检查每个用户看过多少部电影。然后,外部查询仅根据此值过滤出记录:
SELECT *
FROM (
SELECT
Subject_id,
Movie_id,
Variation,
COUNT(*) OVER (PARTITION BY Subject_id) cnt
FROM measures
) x
WHERE cnt > 1
答案 2 :(得分:0)
解决方案最终如下:
SELECT measures.Subject_id, measures.Movie_id, measures.Median_heart_rate AS Variation
FROM measures
WHERE measures.Subject_id IN (SELECT DISTINCT Subject_id FROM measures GROUP BY Subject_id HAVING COUNT(Subject_id) > 1);
答案 3 :(得分:0)
我只会使用exists
:
SELECT m.Subject_id, m.Movie_id,
m.Median_heart_rate AS Variation
FROM measures m
WHERE EXISTS (SELECT 1
FROM measures m2
WHERE m2.Subject_id = m.Subject_id AND
m2.Movie_id <> m.Movie_id
);
如果您的主键确实是measures(Subject_id, Movie_id)
,那么它的性能也应该很好。