【问题标题】:Query with only in where?只在哪里查询?
【发布时间】:2014-11-06 03:28:09
【问题描述】:

sqlite 中是否有类似“only”的关键字?我必须写一个查询来显示只预订红船的水手姓名。所以我目前的查询是:

select s.sname
from sailor s, boat b, reservation r
where s.sname = r.sname
and b.bname = r.bname
and b.color = 'red';

上面查询的问题是它还显示了预定红色+其他颜色船的水手姓名。我的查询结果:

a reserve red boat
a reserve green boat
b reserve red boat

但它应该只显示b,因为他只预订红色船。

【问题讨论】:

    标签: sql sqlite


    【解决方案1】:

    您可以使用NOT EXISTS 子句过滤只有redboat 的水手。

    select r.sname
    from reservation r
    join boat b
    on b.bname = r.bname
    and b.color = 'red'
    and not exists ( select 1 from reservation r2
                     join boat b2
                     on r2.bname = b2.bname
                     and r2.sname = r.sname
                     and b2.color <> 'red' )
    

    【讨论】:

    • 谢谢你,但它也显示选择其他颜色船的水手。
    • @something,我试过了,它给出了正确的结果,这是 sql fiddle sqlfiddle.com/#!7/dbaa2/1
    【解决方案2】:

    存在多个选项。您可以使用NOT IN 运算符,如

    select s.sname
    from sailor s, boat b, reservation r
    where s.sname = r.sname
    and b.bname = r.bname
    and b.color NOT IN (select distinct color from boat where color <> 'red'); 
    

    此外,并非每个水手都会预订一艘船。所以在这种情况下,你最好使用LEFT JOIN 而不是INNER JOIN。另外,我认为你的意思是做一个group by 水手的名字,如下所示

    select s.sname
    from sailor s, 
    left join reservation r on s.sname = r.sname
    left join boat b on b.bname = r.bname
    group by s.sname
    having count(*) <= 1 and b.color = 'red' 
    

    【讨论】:

    • 谢谢您,我已经尝试了您的两个查询,但结果与我的查询相同。
    猜你喜欢
    • 1970-01-01
    • 2020-12-19
    • 2011-08-22
    • 1970-01-01
    • 2017-03-23
    • 1970-01-01
    • 1970-01-01
    • 2016-07-30
    • 2015-07-29
    相关资源
    最近更新 更多