从关系代数翻译成 SQL
Translating from Relational Algebra to SQL
下面的练习要求我将关系代数转换为 SQL 代码。
我对关系代数还不是很熟悉,但我尝试在SQL中编写以下关系,但我认为我犯了一些错误。
**> [Customer × Product ]―[π{Cid, Name, Pid, Label}(Customer ⋈ Orders ⋈ line_item)]**
SELECT * FROM Customer, Product WHERE Cid, Name, Pid, Label NOT IN
(SELECT Cid, Name, Pid, Label FROM Customer NATURAL JOIN Orders
NATURAL JOIN line_item);
这个代数关系我真的不知道怎么处理:
**> πName,Name2(σCid<Cid2 (πCid,Name,Pid (Customer ⋈ Orders ⋈ line_item)
⋈ βCid→Cid2,Name→Name2 (πCid,Name,Pid (Customer ⋈ Orders ⋈
line_item))))**
如果您能向我解释处理此类代数关系的推理过程,我们将不胜感激。
对于第一个查询,它看起来几乎是正确的,除了我不认为你可以用 NOT IN
给出多个列。我会使用 WHERE NOT EXISTS
:
SELECT * FROM Customer c1, Product
WHERE NOT EXISTS
(SELECT Cid, Name, Pid, Label FROM Customer c2
NATURAL JOIN Orders
NATURAL JOIN line_item
WHERE c1.Cid = c2.Cid); -- assuming Cid is a primary key of your customer table
对于第二部分,
πName,Name2(σCid<Cid2 (πCid,Name,Pid (Customer ⋈ Orders ⋈ line_item)
⋈ βCid→Cid2,Name→Name2 (πCid,Name,Pid (Customer ⋈ Orders ⋈
line_item))))
可以这么写
R1 = (πCid,Name,Pid (Customer ⋈ Orders ⋈ line_item))
R2 = (πCid,Name,Pid (Customer ⋈ Orders ⋈ line_item) ⋈ βCid→Cid2,Name→Name2 R1))
R3 = πName,Name2(σCid<Cid2 R2)
这将翻译:
R1 = (SELECT Cid, Name, Pid FROM Customer NATURAL JOIN Orders NATURAL JOIN line_item)
R2 = (SELECT Cid, Name, Pid FROM Customer NATURAL JOIN Orders NATURAL JOIN line_item NATURAL JOIN (SELECT Cid as Cid2, Name as Name2 FROM R1))
R3 = SELECT Name, Name2 FROM R2 WHERE Cid < Cid2
下面的练习要求我将关系代数转换为 SQL 代码。
我对关系代数还不是很熟悉,但我尝试在SQL中编写以下关系,但我认为我犯了一些错误。
**> [Customer × Product ]―[π{Cid, Name, Pid, Label}(Customer ⋈ Orders ⋈ line_item)]**
SELECT * FROM Customer, Product WHERE Cid, Name, Pid, Label NOT IN
(SELECT Cid, Name, Pid, Label FROM Customer NATURAL JOIN Orders
NATURAL JOIN line_item);
这个代数关系我真的不知道怎么处理:
**> πName,Name2(σCid<Cid2 (πCid,Name,Pid (Customer ⋈ Orders ⋈ line_item)
⋈ βCid→Cid2,Name→Name2 (πCid,Name,Pid (Customer ⋈ Orders ⋈
line_item))))**
如果您能向我解释处理此类代数关系的推理过程,我们将不胜感激。
对于第一个查询,它看起来几乎是正确的,除了我不认为你可以用 NOT IN
给出多个列。我会使用 WHERE NOT EXISTS
:
SELECT * FROM Customer c1, Product
WHERE NOT EXISTS
(SELECT Cid, Name, Pid, Label FROM Customer c2
NATURAL JOIN Orders
NATURAL JOIN line_item
WHERE c1.Cid = c2.Cid); -- assuming Cid is a primary key of your customer table
对于第二部分,
πName,Name2(σCid<Cid2 (πCid,Name,Pid (Customer ⋈ Orders ⋈ line_item)
⋈ βCid→Cid2,Name→Name2 (πCid,Name,Pid (Customer ⋈ Orders ⋈
line_item))))
可以这么写
R1 = (πCid,Name,Pid (Customer ⋈ Orders ⋈ line_item))
R2 = (πCid,Name,Pid (Customer ⋈ Orders ⋈ line_item) ⋈ βCid→Cid2,Name→Name2 R1))
R3 = πName,Name2(σCid<Cid2 R2)
这将翻译:
R1 = (SELECT Cid, Name, Pid FROM Customer NATURAL JOIN Orders NATURAL JOIN line_item)
R2 = (SELECT Cid, Name, Pid FROM Customer NATURAL JOIN Orders NATURAL JOIN line_item NATURAL JOIN (SELECT Cid as Cid2, Name as Name2 FROM R1))
R3 = SELECT Name, Name2 FROM R2 WHERE Cid < Cid2