数据库查询说明

时间:2010-11-08 12:58:41

标签: sql sql-server-2005

我无法理解以下查询如何带来适当的结果请解释我

考虑航空公司数据库的以下关系模式。

customer(id, name, age, gender)
onFlight(id, flightNo, flightDate)
flightInfo(flightNo, fromCity, toCity, startTime, duration

。航班(flightNo,flightDate)上至少有两个客户

SELECT f1.flightNo, f1.flightDate
FROM onFlight as f1, onFlight as f2
WHERE f1.flightNo = f2.flightNo AND f1.flightDate=f2.flightDate AND __________________ f1.id <> f2.id

我可以写这个查询而不是......

select flightNo, flightDate count(id) from onFlight groupBy(id) having count(id)>1

2 个答案:

答案 0 :(得分:3)

SELECT  f1.flightNo, f1.flightDate
FROM    onFlight as f1, onFlight as f2
WHERE   f1.flightNo = f2.flightNo
        AND f1.flightDate = f2.flightDate
        AND f1.id <> f2.id

这可以为每个flightNo / flightDate对建立所有航班的交叉连接(所有可能的组合),这将选择所有不匹配的记录。

这不是最有效的方法,因为如果有两个以上的客户,它将返回所有重复项。

更有效的方式是:

SELECT  flightNo, flightDate
FROM    onFlight
GROUP BY
        flightNo, flightDate
HAVING  COUNT(*) >= 2

您可以在此处将2替换为任何其他号码。

答案 1 :(得分:1)

它可能更有效:

SELECT f1.flightNo, f1.flightDate, COUNT(*)
FROM onFlight AS f1, onFlight AS f2
WHERE f1.flightNo = f2.flightNo AND f1.flightDate=f2.flightDate 
GROUP BY f1.flightNo, f1.flightDate
HAVING COUNT(*)>=2