gpt4 book ai didi

sql - 保持 SQL 干燥

转载 作者:行者123 更新时间:2023-11-29 04:31:11 26 4
gpt4 key购买 nike

这是我正在运行的 MySQL 查询:

-- get the sid of every supplier who does not supply both a red and green part
SELECT Suppliers.sid, Parts.color
FROM Suppliers
JOIN Catalog ON Catalog.sid = Suppliers.sid
JOIN Parts ON Parts.pid = Catalog.pid
WHERE Suppliers.sid NOT IN (
SELECT Suppliers.sid
FROM Suppliers
JOIN Catalog ON Catalog.sid = Suppliers.sid
JOIN Parts ON Parts.pid = Catalog.pid
WHERE Parts.color IN ('red', 'green')
GROUP BY Suppliers.sid
HAVING COUNT(DISTINCT Parts.color) = 2
)
ORDER BY Suppliers.sid DESC;

如您所见,这重复了两次:

FROM Suppliers
JOIN Catalog ON Catalog.sid = Suppliers.sid
JOIN Parts ON Parts.pid = Catalog.pid

如何才能只声明一次并引用两次?或者这是否表明我的整个查询存在某种缺陷?

当我使用相同的三行代码运行 15 个不同的查询时,问题会更加严重。

最佳答案

如果您要在整个系统中继续使用表的关系,那么您要查看的内容称为 view .

关于sql - 保持 SQL 干燥,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2304723/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com