内部加入就像交叉连接?

时间:2013-03-06 16:45:25

标签: sql sql-server join

我正在尝试创建一个在多个表之间创建连接的查询。 这是一个例子:

select b.name as state, c.name as city, sum(qnt) as total_quantity 
from qtn_table a, state_table b, city_table c
where a.state_id = b.id and a.city_id = c.id
and a.year = 2011 and a.product = 1 group by b.name, c.name

还尝试使用Inner Join:

select b.name as state, c.name as city, sum(qnt) as total_quantity 
from qtn_table a
inner join state_table b ON a.state_id = b.id
inner join city_table c ON a.city_id = c.id
where a.year = 2011 and a.product = 1 group by b.name, c.name

结果是一样的。

它应该只返回一个拥有自己状态的城市:

state    city    total_quantity
NY       A
NY       B
Texas    C
Texas    D
Cali     E
Cali     F

但它正在返回奇怪的结果,例如:

state    city     total_quantity
NY       A
Texas    A
Cali     A
NY       B
...
...

在一个典型的交叉连接中,我认为它应该出现在所有州的城市A上,但它只涉及一些而不是全部,这是一个更奇怪的情况。

我做错了什么?

1 个答案:

答案 0 :(得分:3)

您错过了从state_tablecity_table的联接,并且它为该表中的每个州或每个具有相同名称的城市的状态返回一行(似乎至少)。我在AND state_table.state = city_table.state中添加了您的查询

select b.name as state, c.name as city, sum(qnt) as total_quantity 
from qtn_table a
 inner join state_table b ON a.state_id = b.id
 inner join city_table c ON a.city_id = c.id AND state_table.state = city_table.state
where a.year = 2011 
and a.product = 1 
group by b.name, c.name