简体   繁体   中英

mysql - retrieving a value using sub-select

SELECT  snr, nsname FROM type
WHERE snr in (SELECT snr FROM diet 
WHERE foodnr in (SELECT foodnr FROM food WHERE foodtype = 'FISH' ));

there are more animals that eat the same kind of food BUT eat different types of food in my database, how do i get the animals that only eat that type of food and nothing else.

bah this is impossible to answer without my entire database i feel like an ass just asking this because its so vague but what i am trying to do is i need to filter out the animals that have more foodtypes besides FISH

JOIN the tables instead, like so:

SELECT t.snr, t.nsname 
FROM type t 
INNER JOIN diet d ON t.snr = d.snr
INNER JOIN food f ON t.foodnr = f.foodnr
WHERE t.foodtype = 'FISH'
GROUP BY t.foodtype
HAVING COUNT(DISTINCT t.foodtype) = 1;

Note I'm assuming the following about your schema:

  • TYPE: snr, nsname
  • DIET: snr, foodnr
  • FOOD: foodnr, foodtype

You can use a NOT EXISTS :

SELECT t.snr, t.nsname 
FROM type t 
INNER JOIN diet d ON t.snr = d.snr
INNER JOIN food f ON d.foodnr = f.foodnr
WHERE f.foodtype = 'FISH'
AND NOT EXISTS
(
    SELECT 1 
    FROM diet dd
    INNER JOIN food ff ON dd.foodnr = ff.foodnr
    WHERE ff.foodtype <> 'FISH'
    AND dd.snr = t.snr
)

Or you can use an anti-join pattern:

SELECT t.snr, t.nsname 
FROM type t 
INNER JOIN diet d ON t.snr = d.snr
INNER JOIN food f ON d.foodnr = f.foodnr AND f.foodtype = 'FISH'
LEFT OUTER JOIN diet dd ON t.snr = dd.snr AND f.foodnr <> dd.foodnr
WHERE f.foodtype = 'FISH'
AND dd.snr IS NULL

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