【发布时间】:2015-04-20 04:38:25
【问题描述】:
考虑到以下关系movie {country,major_genre,production_year, run_time, title,我想列出除西班牙以外的所有国家,在该国家/地区制作的电影,只要其中至少有两部。
我写了两个查询,它们以某种方式产生了不同的结果。似乎第一个是正确的,但在我看来,它们是平等的。我正在学习 SQL。有人可以帮助解释这些差异吗?谢谢你的帮助!
第一个:
SELECT m1.country, m1.production_year, m1.title
FROM movie m1
WHERE m1.country <> "Spain"
AND m1.country
IN (
SELECT m2.country
FROM movie m2
GROUP BY m2.country //select only the ones with at least 2 movies
HAVING COUNT( * ) >=2
)
ORDER BY m1.country ASC , m1.production_year DESC
第二个:
SELECT m1.country, m1.production_year, m1.title
FROM movie m1
WHERE m1.country <> "Spain"
GROUP BY m1.country
HAVING COUNT( * ) >=2 //the country selected should have count of at least 2 rows
ORDER BY m1.country ASC , m1.production_year DESC
【问题讨论】:
-
我的第一个问题是,第二个查询有效吗?
-
看起来像一个 MySQL 查询,它放宽了与 GROUP BY 子句相关的规则。仅供参考,第二个查询不正确,因为您必须列出 SELECT 列表中的 GROUP BY 子句中的所有列
-
我在 select 语句中看到“m1.country, m1.production_year, m1.title”,但在 group by 你只有 m1.country
-
是的,第二个有效..
-
但是在group by中加入“m1.country, m1.production_year, m1.title”后还是不正确
标签: sql count group-by aggregate-functions having-clause