1

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

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

还尝试了内部联接:

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 上,但它只是在其中一些而不是全部上出现,这是一个更奇怪的情况。

我究竟做错了什么?

4

1 回答 1

3

您缺少从state_tableto的连接,city_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
于 2013-03-06T16:48:14.720 回答