HAVING
可以而且应该使用;我用 SQLite 2.8.17 和 3.6.22 进行了测试。
要获得具有两个评分的电影:
SELECT mid
FROM movie
GROUP BY mid
HAVING COUNT(*) = 2;
然后你可以在一个IN
:
SELECT *
FROM movie
WHERE mid in (
SELECT mid
FROM movie
GROUP BY mid
HAVING COUNT(*) = 2
);
或加入它:
SELECT movie.*
FROM movie
JOIN (
SELECT mid
FROM movie
GROUP BY mid
HAVING COUNT(*) = 2
) those_with_two
ON movie.mid = those_with_two.mid;
完整的测试用例设置,供参考:
$ sqlite3 so-movie
create table movie (
mid varchar(10),
rating varchar(10)
);
insert into movie values('M1','R1');
insert into movie values('M1','R2');
insert into movie values('M2','R3');
insert into movie values('M3','R4');
我说HAVING
应该使用有几个原因:
- 如果您想要多个子句,它会更灵活,例如具有两个评级或 mid='M3' 的电影
- 它会比 Lamak 的第二个解决方案执行得更好(解释计划显示打了三个表)
- 更容易阅读和理解