循环的SQL查询

时间:2017-09-24 20:37:36

标签: sql relational-division

我有两张表TravelHistoryLikesToVisit

两者都有两个字段SSNAirportId

如果客户访问过他喜欢访问的所有城市,查询的查询是什么?

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

这将为您提供那些没有前往他们所有喜欢的人的非独特名单。

SELECT * FROM LikesToVisit AS lv LEFT OUTER JOIN TravelHistory AS th ON lv.SSN = th.SSN AND lv.AirportID = th.AirportID WHERE lv.SSN = NULL

或者,也可以使用子查询

SELECT * FROM LikesToVisit AS lv WHERE lv.SSN NOT IN (SELECT SSN FROM TravelHistory AS th WHERE th.SSN = lv.SSN AND th.AirportID = lv.AirportID)

答案 1 :(得分:0)

此查询将提供他喜欢访问但尚未访问过的所有城市。

SELECT SSN, Airportid
  FROM LikesToVisit
MINUS
SELECT SSN, Airportid
  FROM TravelHistory

选择不在上述结果集中的所有SSN将为您提供访问过他喜欢的所有人的列表

SELECT SSN, 'Visited all he liked' 
  FROM Travelhistory 
 WHERE SSN not in (select distinct SSN 
                     FROM( SELECT SSN, Airportid
                             FROM LikesToVisit
                            MINUS
                           SELECT SSN, Airportid
                             FROM TravelHistory)