我试图理解为什么自然连接在我的两个表上的 sql 中无法正常工作:
bookno | title
--------+----------------------
2001 | Databases
2012 | Geometry
2010 | Philosophy
2008 | DataScience
2011 | Anthropology
2003 | Networks
2013 | RealAnalysis
2006 | SQL
2002 | OperatingSystems
2007 | ProgrammingLanguages
2009 | Calculus
2005 | DiscreteMathematics
2014 | Topology
2004 | AI
(14 rows)
和
price | bookno | title | b2price | sid | sname
-------+--------+----------+---------+------+-----------
70 | 2014 | Topology | 70 | 1022 | Joeri
80 | 2012 | Geometry | 80 | 1008 | Emma
80 | 2012 | Geometry | 80 | 1010 | Linda
80 | 2012 | Geometry | 80 | 1020 | Ahmed
80 | 2012 | Geometry | 80 | 1004 | Chin
80 | 2012 | Geometry | 80 | 1023 | Chris
80 | 2012 | Geometry | 80 | 1007 | Catherine
80 | 2012 | Geometry | 80 | 1017 | Ellen
70 | 2014 | Topology | 70 | 1023 | Chris
80 | 2012 | Geometry | 80 | 1012 | Eric
80 | 2012 | Geometry | 80 | 1006 | Ryan
80 | 2012 | Geometry | 80 | 1002 | Maria
80 | 2012 | Geometry | 80 | 1014 | Filip
80 | 2012 | Geometry | 80 | 1005 | John
80 | 2012 | Geometry | 80 | 1009 | Jan
80 | 2012 | Geometry | 80 | 1013 | Lisa
80 | 2012 | Geometry | 80 | 1011 | Nick
80 | 2012 | Geometry | 80 | 1003 | Anna
(18 rows)
第二个表是使用几个交叉连接和不同表创建的表。这种自然连接的结果不应该是:
bookno | title
--------+----------------------
2012 | Geometry
2014 | Topology
但相反,它输出的只是第一个表。为什么会这样?确切的代码是:
select distinct b.bookno, b.title
from book b, student s
natural join (select distinct b1.price, b2.bookno, b2.title, b2.price, s1.sid, s1.sname
from buys t cross join book b1 cross join book b2 cross join student s1
where b1.price > 50 and s1.sid = t.sid and
t.bookno = b1.bookno and b2.price = b1.price) q0;