开发者

SQL 3 column query on condition

I'm still pretty new to SQL and have a table something like the following

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

I was wondering if there is a single query that can be done to check a particular street, to see if there is a car that all the family's have?

So for instance in the above table the query would only return BMW fo开发者_运维百科r Mayfair as all the family's on Mayfair own a BMW.

I'm only using XAMPP at the moment with MySql so don't have any fancy server or anything setup etc...

Thanks


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
         )

or:

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
        )
  )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜