2013-03-06 21 views
1

我想創建一個查詢創建幾個表之間的連接。 下面是一個例子:Inner 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 

還與內試圖加入:

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,但它只是在一些而不是所有的城市上展開,這是一種更加陌生的情況。

我在做什麼錯?

+0

可以ypu給樣品recors與您想要的結果? – 2013-03-06 16:46:30

回答

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 
+0

就是這樣!非常感謝!我完全錯過了! – 2013-03-06 17:00:55