简体   繁体   中英

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.

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.

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:

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:-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM