[英]How do I write sql without subqueries for the following query
SELECT C.pid
FROM Catalog C, Suppliers S
WHERE S.sname = ‘Yosemite Sham’ AND C.sid = S.sid
AND C.cost ≥ ALL (Select C2.cost
FROM Catalog C2, Suppliers S2
WHERE S2.sname = ‘Yosemite Sham’ AND C2.sid = S2.sid)
First, learn to use proper, explicit JOIN
syntax. 首先,学习使用正确的显式JOIN
语法。
Then, if you assume that the maximum cost occurs only once, you can do: 然后,如果您假设最高成本只出现一次,您可以:
SELECT C.pid
FROM Catalog C JOIN
Suppliers S
ON C.sid = S.sid
WHERE S.sname = 'Yosemite Sham'
ORDER BY c.Cost DESC
FETCH FIRST 1 ROW ONLY ;
Note that the last clause is ANSI standard SQL. 请注意,最后一个子句是ANSI标准SQL。 Some databases use other methods for the same functionality. 某些数据库使用其他方法来实现相同的功能。
Without this assumption, basically all reasonable methods use a subquery. 没有这个假设,基本上所有合理的方法都使用子查询。 Here is one that doesn't: 这是一个没有:
SELECT C.pid
FROM Catalog C JOIN
Suppliers S
ON C.sid = S.sid LEFT JOIN
Catalog C2
ON C2.sid = C.sid AND
C2.Cost > C.Cost
WHERE S.sname = 'Yosemite Sham' AND c2.Cost IS NULL
ORDER BY c.Cost DESC;
Note: This assumes that sid
is 1-1 with sname
. 注意:这假设sid
为1-1并且具有sname
。 That is a convenience (which is likely to be true) and helps avoid an extra join to Suppliers
. 这是一种便利(可能是真的)并且有助于避免额外加入Suppliers
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.