[英]Query with subquery and having count(distinct) condition
I'm attempting to create a query that lists the name and id of every horse which has finished in the top 3 in an event 2 or more times.我正在尝试创建一个查询,其中列出了在一个事件中两次或多次进入前 3 名的每匹马的名称和 ID。
These are the two tables which I'm using:这是我正在使用的两个表:
And this is the query I've come up with:这是我想出的查询:
SELECT horse.horse_id, horse.name FROM horse
INNER JOIN
(SELECT horse_id
FROM entry
WHERE place in ('1', '2', '3')
HAVING count(distinct place) >1)
entry on horse.horse_id=entry.horse_id;
I've clearly done something wrong, because when I run this query only flash comes up, when it should be flash and boxer.我显然做错了什么,因为当我运行这个查询时,只有 flash 出现,而它应该是 flash 和 boxer。
You condition counts the number of distinct places a horse finished, which is wrong, as you'd definitely like to include a horse which finished first twice.您的条件计算了一匹马完成的不同位置的数量,这是错误的,因为您肯定希望包括一匹先完成两次的马。 Moreover, you're missing a
group by
clause:此外,您还缺少
group by
子句:
SELECT horse.horse_id, horse.name
FROM horse
INNER JOIN (SELECT horse_id
FROM entry
WHERE place IN (1, 2, 3) -- should probably be numbers, BTW
GROUP BY horse_id
HAVING COUNT(*) > 1) entry ON horse.horse_id = entry.horse_id;
You missed group by condition.你错过了按条件分组。
SELECT horse.horse_id, horse.name FROM horse
INNER JOIN
(SELECT horse_id
FROM entry
WHERE place in ('1', '2', '3')
group by horse_id
HAVING count(*) >1)
entry on horse.horse_id=entry.horse_id;
Here you go.干得好。
SELECT horse.horse_id, horse.name FROM horse
INNER JOIN
(SELECT horse_id
FROM entry
WHERE place in ('1', '2', '3')
GROUP BY horse_id
HAVING count(*) >1)
entry on horse.horse_id=entry.horse_id;
As others have pointed out you are missing a GROUP BY clause, but I think you could avoid using a sub query to simplify the query:-正如其他人指出的那样,您缺少 GROUP BY 子句,但我认为您可以避免使用子查询来简化查询:-
SELECT horse.horse_id, horse.name
FROM horse
INNER JOIN entry
ON horse.horse_id = entry.horse_id
WHERE entry.place IN ('1', '2', '3')
GROUP BY horse.horse_id
HAVING COUNT(*) > 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.