sql查询中的否定动词

sql查询中的否定动词,sql,Sql,我的问题很简单。如何编写一个否定某些内容的查询?我不是指不健康的状况。例如,我必须选择至少预订了一个等级大于9的PensionAc_type_代码,但没有预订任何等级小于9的三星级酒店的所有游客 我的桌子: 游客 id (pk) name email 预订 id_tourist (pk) id_accomodation (pk) 住宿 id_accomodation (pk) acc_type_code (fk) nr_of_stars rating price 住宿类型 acc_type

我的问题很简单。如何编写一个否定某些内容的查询?我不是指不健康的状况。例如,我必须选择至少预订了一个等级大于9的PensionAc_type_代码,但没有预订任何等级小于9的三星级酒店的所有游客

我的桌子:

游客

id (pk)
name
email
预订

id_tourist (pk)
id_accomodation (pk)
住宿

id_accomodation (pk)
acc_type_code (fk)
nr_of_stars
rating
price
住宿类型

acc_type_cde (pk)
acc_type_name
我所尝试的:

SELECT t.id as id_tourist, t.name, t.email from Tourist t,
JOIN Booking b on (t.id = b.id_tourist)
JOIN Accomodation a on (b.id_accomodation = a.id_accomodation)
JOIN AccType at on (a.acc_type_code = at.acc_type_code)
WHERE a.rating > 9 AND .. ?
我被封锁了。有什么建议吗?

您可以使用左外部联接来定位要从查询中排除的记录,然后在WHERE条件中过滤掉它们

SELECT t.id as id_tourist, t.name, t.email 
FROM Tourist t
INNER JOIN Booking b on (t.id = b.id_tourist)
INNER JOIN Accomodation a on (b.id_accomodation = a.id_accomodation)
INNER JOIN AccType at on (a.acc_type_code = at.acc_type_code)
LEFT OUTER JOIN Accomodate a2 on (b.id_accomodation = a2.id_accomodation) AND a2.nr_of_stars = 3 AND a2.rating < 9
WHERE a.rating > 9 AND a2.id_accomodation IS NULL
注意:您可能需要在NOT EXISTS子句中添加更多联接,以定位应排除的记录。我不知道您的数据。

这里有一个左连接、反连接方法:

SELECT t.id as id_tourist, t.name, t.email 
FROM Tourist t,
JOIN Booking b ON t.id = b.id_tourist
JOIN Accomodation a ON b.id_accomodation = a.id_accomodation
                   AND a.rating > 9
JOIN AccType at ON a.acc_type_code = at.acc_type_code
LEFT JOIN (SELECT t.id
           FROM Tourist t
           JOIN Booking b ON t.id = b.id_tourist
           JOIN Accomodation a ON b.id_accomodation = a.id_accomodation
                              AND a.rating < 9
                              AND a.nr_of_stars = 3
          ) a2 ON a2.id = t.id
WHERE a2.id IS NULL
外部查询只找到预订了9级以上酒店的游客t.id。内部查询只找到预订了三星级酒店的游客t.id,低于9级


通过在它们之间进行左连接,并将我们的结果仅限于a2.id为空的不匹配的结果,我们只剩下预订了9级以上酒店的人,而没有预订9级以下的三星级酒店的人。

应该很容易,因为使用的是不存在的

SELECT t.id as id_tourist, t.name, t.email from Tourist t,
JOIN Booking b on (t.id = b.id_tourist)
JOIN Accomodation a on (b.id_accomodation = a.id_accomodation)
JOIN AccType at on (a.acc_type_code = at.acc_type_code)
WHERE a.rating > 9 AND 
NOT EXISTS (
your query to get the same tourist_Id and has booked a 3 start hotel and under 9 ratings
)

使用不存在…这是4分钟前发布的devlin答案的副本。@DanBracuk如果是你的,请删除你的否决票,或者解释这是如何重复的。我认为你已经否决了正确的答案,OP可能因为这个或你的评论而没有尝试。它不起作用。如果我有一个名为ana:id=1的用户,在预订:1-1、1-3、1-4和住宿:id_acc:1、nr_star:3、评级7、id_acc:3、nr_star:3、评级17和id_acc:4、nr_star=1、评级1中,该用户将在不应该显示时显示。
SELECT t.id as id_tourist, t.name, t.email from Tourist t,
JOIN Booking b on (t.id = b.id_tourist)
JOIN Accomodation a on (b.id_accomodation = a.id_accomodation)
JOIN AccType at on (a.acc_type_code = at.acc_type_code)
WHERE a.rating > 9 AND 
NOT EXISTS (
your query to get the same tourist_Id and has booked a 3 start hotel and under 9 ratings
)