我们假设您有一组这样的表:
Museum(M_name,State) Artist(A_name,Country) Artwork(Id,Title,M_name*,A_name*)
我想获得加州博物馆的所有名称,例如达芬奇没有艺术品。
关于如何做到这一点的任何解释都会对我有所帮助!
到目前为止,我所做的是:
SELECT M_name FROM Museum,Artwork WHERE Artwork.M_name*=Museum.M_name AND State="California"
但是我不得不排除包含特定作者作品的博物馆。有些人在最后一行之后建议这样的事情:
AND A_name NOT EXIST ( SELECT A_name FROM Artwork WHERE A_name="Da-vinci")
我明白命令EXIST返回0/1并取决于子请求结果,但我无法想象为什么它会在这种情况下起作用...
答案 0 :(得分:1)
尝试这种方法,它使用NOT EXISTS:
SELECT DISTINCT m.name, m.town
FROM Museum m
WHERE State = 'California'
AND NOT EXISTS (SELECT * FROM Artwork aw WHERE m.M_name = aw.M__name AND A_name = 'Da-vinci')
答案 1 :(得分:0)
你可以使用连接而不是
select distinct m.name, m.town
from Artwork aw
inner join Museum m on m.M_name = aw.M__name
where aw.A_Name not in ( 'da-vinci');
或使用!=
select distinct m.name, m.town
from Artwork aw
inner join Museum m on m.M_name = aw.M__name
where aw.A_Name != 'da-vinci';
这是不存在的
select distinct m.name, m.town
from Artwork aw
inner join Museum m on m.M_name = aw.M__name
WHERE NOT EXISTS
(
SELECT null
FROM Artwork aw
WHERE aw.A_Name = ( 'da-vinci');
)
答案 2 :(得分:0)
达芬奇没有艺术品的博物馆
SELECT M_name
FROM Artwork
WHERE LOWER(A_Name) NOT IN ('da vinci')
您没有说明如何找出博物馆所处的状态。 (现在我看到你的例子)
加入博物馆餐桌以获得“城镇”
SELECT M_name
FROM Museum
JOIN (
SELECT M_name
FROM Artwork
WHERE LOWER(A_Name) NOT IN ('da vinci')
) AS X ON X.M_name = M_name
WHERE Town='Calafornia'
上面的代码应该与NOT EXISTS()代码相同。事实上,如果你对它们进行解释,它看起来应该是一样的。
答案 3 :(得分:0)
实际上,你已经在你的问题中写了这个问题:
SELECT m.m_name -- I would like to get all the names
FROM museum m -- of museums
WHERE m.state = 'Californa' -- in California
AND NOT EXISTS ( -- that has no
SELECT * FROM artwork aw -- artwork
WHERE aw.m_name = m.m_name -- For THIS museum
AND aw.a_name = 'Da-vinci' -- made by da-vinci
);