自然连接两个具有不同列数且正常工作的表

Natural join on two tables with different number of columns that working properly

我想了解为什么自然连接在我的两个 table 上的 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)

第二个 table 是 table 使用几个交叉连接和不同的 table 制作的。这个自然连接的结果不应该是:

bookno |        title
--------+----------------------
2012 | Geometry
2014 | Topology

但是,它输出的只是第一个table。为什么会这样?确切的代码是:

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;

这是(可怕的)旧语法,会在 book 和 student 之间产生交叉连接:

select distinct b.bookno, b.title
from book b, student s

为显式连接语法重写为:

select distinct b.bookno, b.title
from book b CROSS JOIN student s

但是,如果这就是查询的结构,那么您在 return 中得到的将是 booknotitle,这实际上与以下内容相同:

select b.bookno, b.title
from book b

其余的查询只是噪音。

nb:如果您的结果重复 bookno/title,那么您还没有将 exact 查询复制到问题中