MySQL嵌套查询问题

时间:2014-10-19 19:23:37

标签: mysql sql mysql-workbench

我正在使用MySQL Workbench 6.2 CE。

我有以下表格列:

Artist (artistId, name, dateOfBirth, dateOfDeath, homeCountry)
Picture (picId, name, artistId, value)
Museum (museumName, city, country)
Exhibited (picId, museumName, from, to)

我想要实现这个问题的答案:

The museums (with name and city) which exhibit or exhibited pictures
of **all** the artists born between 1920 and 1950.

到目前为止我已经尝试过查询:

SELECT museum.museumName, museum.city, COUNT(artist.artistId) AS C FROM museum

INNER JOIN exhibited ON exhibited.museumName = museum.museumName
INNER JOIN picture ON picture.picId = exhibited.picId
INNER JOIN artist ON artist.artistId = picture.artistId

WHERE dateOfBirth BETWEEN 2000 AND 2004
GROUP BY museum.museumName
HAVING COUNT(C) = (SELECT COUNT(*) FROM artist WHERE dateOfBirth BETWEEN 2000 AND 2004);

------------------------

SELECT museumName, city FROM museum WHERE museumName IN 
(SELECT museumName FROM exhibited WHERE picId IN
 (SELECT picId FROM Picture WHERE artistId IN 
  (
   SELECT artistId FROM artist WHERE dateOfBirth BETWEEN 2000 AND 2004
  )
 )
);

我还尝试了其他查询但无法提供我删除的查询,因为他们没有帮助。

哪些查询可以打印询问的数据?

1 个答案:

答案 0 :(得分:0)

您的第一个查询非常接近。而不是count(c),你需要计算艺术家的数量,以及让年代变得正确:

HAVING COUNT(DISTINCT artistId) = (SELECT COUNT(*) FROM artist WHERE dateOfBirth BETWEEN 1920 AND 1950);

您还需要修复where子句。现在在博物馆展出的艺术家不是那么多2000年后出生的艺术家。