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

时间:2017-10-30 05:18:57

标签: sql postgresql join natural-join

我试图理解为什么自然连接在我的两个表上的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;

1 个答案:

答案 0 :(得分:-1)

这是(可怕的)旧语法在书和学生之间产生交叉连接:

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

重写为显式连接语法,它是:

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

但是,如果从字面上看,查询的结构如何,那么你得到的只是booknotitle,它实际上与以下内容相同:

select b.bookno, b.title
from book b

你们其他人的查询只是噪音。

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