0

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

1 回答 1

-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

但是,如果这就是查询的结构,那么您将得到的回报将是booknoand title,这实际上与以下内容相同:

select b.bookno, b.title
from book b

你们其余的查询只是噪音。

注意:如果您的结果重复 bookno/title 那么您没有将确切的查询复制到问题中

于 2017-10-30T05:46:18.503 回答