我正在学习 SQL SELECT 查询,并寻求一些提示:)
我找到了一个有任务的网站。当我尝试解决其中之一时,我有两种不同的解决方案。他们看起来和我一样,但不一样。
您能否解释一下为什么这些查询不相等?
SELECT DISTINCT Product.maker
FROM Product
JOIN Laptop ON Product.model = Laptop.model
WHERE Laptop.speed >= 750
INTERSECT
SELECT DISTINCT Product.maker
FROM Product
JOIN PC ON Product.model = PC.model
WHERE PC.speed >= 750
AND
SELECT DISTINCT Product.maker
FROM Product
JOIN Laptop ON Product.model = Laptop.model
JOIN PC ON Product.model = PC.model
WHERE PC.speed >= 750 AND Laptop.speed >= 750
谢谢!
更新:
另一个解决方案
SELECT DISTINCT maker FROM Product
JOIN pc ON PC.model = Product.model AND type = 'PC' AND pc.speed > = 750
WHERE maker IN
(SELECT maker FROM Product
JOIN Laptop ON Laptop.model = Product.model AND type = 'Laptop' AND Laptop.speed > = 750)
还有一个,但最快的:
SELECT Product.maker
FROM Product
JOIN Laptop
ON Product.model = Laptop.model
AND Laptop.speed > = 750
AND maker IN(
SELECT maker
FROM Product
JOIN PC
ON Product.model = PC.model
AND PC.speed > = 750
)
答案 0 :(得分:2)
相交版本允许每个联接之间的模型不同,但是单个查询(第二个)版本要求模型相同。
要更正第二个版本,请使用left join
s并将speed
上的条件移到联接条件中:
SELECT DISTINCT Product.maker
FROM Product
LEFT JOIN Laptop ON Product.model = Laptop.model
AND Laptop.speed >= 750
LEFT JOIN PC ON Product.model = PC.model
AND PC.speed >= 750