简体   繁体   中英

Selecting distinct values in MySQL

I'm having trouble finding the solution to the following question:

Which suppliers (lev) can only supply articles that are being sold by the hobby department?

  • The suppliers are in the table leverancier
  • The articles are in the table artikel
  • The table inkart connects leverancier and artikel
  • The departments are in the table afdeling
  • The table verkart connects artikel and afdeling

在此输入图像描述

The query I got so far is:

SELECT DISTINCT leverancier.lev 
FROM leverancier

JOIN inkart ON leverancier.lev = inkart.lev
JOIN artikel ON inkart.art = artikel.art
JOIN verkart ON artikel.art = verkart.art
JOIN afdeling ON verkart.afd = afdeling.afd

WHERE afdnaam = 'Hobby'

But this still includes suppliers who, besides hobby articles, also supply other articles. What would be the best way to filter them out?

SELECT DISTINCT leverancier.lev , AFDNAAM
FROM leverancier
JOIN inkart ON leverancier.lev = inkart.lev
JOIN artikel ON inkart.art = artikel.art
JOIN verkart ON artikel.art = verkart.art
JOIN afdeling ON verkart.afd = afdeling.afd
WHERE AFDNAAM = 'HOBBY'
EXCEPT
SELECT DISTINCT leverancier.lev , AFDNAAM
FROM leverancier
JOIN inkart ON leverancier.lev = inkart.lev
JOIN artikel ON inkart.art = artikel.art
JOIN verkart ON artikel.art = verkart.art
JOIN afdeling ON verkart.afd = afdeling.afd
WHERE AFDNAAM <> 'HOBBY'

I think the easiest way to solve this problem is using aggregation:

SELECT leverancier.lev , AFDNAAM
FROM leverancier JOIN
     inkart
     ON leverancier.lev = inkart.lev JOIN
     artikel
     ON inkart.art = artikel.art JOIN
     verkart ON artikel.art = verkart.art JOIN
     afdeling ON verkart.afd = afdeling.afd
GROUP BY leverancier.lev
HAVING MIN(AFDNAAM) = MAX(AFDNAAM) and
       MIN(AFDNAAM) = 'HOBBY';

That is, 'HOBBY' is the only department in the supplier data.

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