1066 - 不是唯一的表/别名:'zipcodes'

时间:2013-11-27 07:54:53

标签: sql database mysql-error-1064 yii-extensions

这是我的疑问:

SELECT 
test.zipcodes.ZIP,
test.zipcodes.State,
test.dealers.dealer_name,
test.dealers.address1,
test.dealers.address2,
test.dealers.city,
test.dealers.state,
locator.locations.storename,
locator.locations.address,
locator.locations.city,
locator.locations.state
FROM
test.dealers ,
locator.locations ,
test.zipcodes
INNER JOIN 
test.zipcodes ON test.zipcodes.State = test.dealers.state AND test.zipcodes.State =  
locator.locations.state 
WHERE test.zipcodes.ZIP = 123456

[Err] 1066 - 不唯一的表/别名:'zipcodes'

数据库:

1- test->(database)->zipcodes(table)
2- test->(database)->dealers(table)
3- locator->(database)->locations(table)

我想以某种方式获取结果,当我从test.zipcodes搜索ZIP时,它从该表中获取该zip的状态,然后在test.dealerslocator.locations中检查此特定状态table返回来自该状态的两个表的集合结果。

2 个答案:

答案 0 :(得分:1)

这是连接表的正确语法

SELECT distinct 
       test.zipcodes.ZIP,
       test.zipcodes.State,
       test.dealers.dealer_name,
       test.dealers.address1,
       test.dealers.address2,
       test.dealers.city,
       test.dealers.state,
       locator.locations.storename,
       locator.locations.address,
       locator.locations.city,
       locator.locations.state
FROM test.dealers
INNER JOIN test.zipcodes ON test.zipcodes.State = test.dealers.state
inner join locator.locations on test.zipcodes.State = locator.locations.state 
WHERE test.zipcodes.ZIP = 123456

答案 1 :(得分:1)

问题是您要从test.zipcodes 选择两次,而不为这两个表提供别名。虽然快速修复是添加表别名,但基础问题可能是查询中的错误。

你真的想从test.zipcodes选择两次吗?


您现在面临的问题是无法以有意义的方式合并经销商和地点 假设您在某个州有3个经销商和5个地点。你想看到:

DEALER   STORE
===============
dealer1  store1
dealer1  store2
dealer1  store3
dealer1  store4
dealer1  store5
dealer2  store1
dealer2  store2
dealer2  store3
dealer2  store4
dealer2  store5
dealer3  store1
dealer3  store2
dealer3  store3
dealer3  store4
dealer3  store5

但也许那些是你提到的'重复'。它们不是重复的,因为经销商和商店的每个组合都是独一无二的。但也许你期待:

DEALER   STORE
===============
dealer1  store1
dealer2  store2
dealer3  store3
         store4
         store5

后者的问题在于经销商和地点之间没有任何有意义的关系,他们恰好在同一条线上。

如果是你想要的前者:

SELECT 
  zc.zip,
  zc.state,
  deal.dealer_name,
  deal.address1,
  deal.address2,
  deal.city,
  deal.state,
  loc.storename,
  loc.address,
  loc.city,
  loc.state
FROM test.zipcodes zc
LEFT JOIN test.dealers deal ON (zc.state = deal.state)
LEFT JOIN locator.locations loc ON (zc.state = loc.state)
WHERE zc.zip = 123456