简体   繁体   English

仅在哪里查询?

[英]Query with only in where?

Is there keyword like 'only' in sqlite? 在sqlite中有像“ only”这样的关键字吗? I have to write a query to display the sailor name who have reserved only red boat. 我必须写一个查询来显示只保留红船的水手姓名。 So my current query is: 所以我当前的查询是:

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

The problem with the query above is it also display the sailor name who reserve red + other color boat. 上面查询的问题是它还会显示保留红色+其他颜色船的水手姓名。 My query result: 我的查询结果:

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

but it should display only b since he only reserve red boat. 但它只显示b,因为他只保留红船。

you can use NOT EXISTS clause to filter the sailor with only red boat. 您可以使用NOT EXISTS子句仅用red船过滤水手。

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

There are multiple option present. 存在多个选项。 You can use a NOT IN operator like 您可以使用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'); 

Also, not every sailor will reserve a boat. 此外,并非每个水手都会预定船只。 So in that case, you better off for a LEFT JOIN instead of INNER JOIN . 因此,在这种情况下,您最好选择LEFT JOIN而不是INNER JOIN Also, I think you meant to do a group by sailor name something like below 另外,我想你的意思是按照水手的名字做一个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' 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM