我仍然是SQL的新手,并且有一个类似于以下内容的表
Street | Family | Car
--------------------------------
Mayfair | Jones | BMW
Mayfair | Jones | Ford
Mayfair | Jones | Mazda
Mayfair | Smith | BMW
Mayfair | Fox | BMW
Park Lane | Taylor | Ford
Park Lane | Taylor | Mazda
Park Lane | Cole | BMW
我想知道是否有一个查询可以检查特定的街道,看看是否有一辆所有家庭都有的车?
因此,例如在上表中,由于梅菲尔的所有家族都拥有一辆宝马汽车,所以查询只会返回BMW for Mayfair。
我目前只使用XAMPP与MySql,所以没有任何花哨的服务器或任何设置等...
由于
答案 0 :(得分:4)
SELECT street, car
FROM tableX AS t1
GROUP BY street, car
HAVING COUNT(DISTINCT family)
= ( SELECT COUNT(DISTINCT t2.family)
FROM tableX AS t2
WHERE t2.street = t1.street
)
或:
SELECT DISTINCT street, car --- show streets and cars
FROM tableX AS a
WHERE NOT EXISTS --- where there is no
( SELECT Family --- family
FROM tableX AS f
WHERE f.Street = a.Street --- in that street
AND NOT EXISTS --- that hasn't
( SELECT Car
FROM tableX AS c
WHERE c.Family = f.Family
AND c.Car = a.Car --- that car
)
)