无法加入3个表(不是唯一的表/别名)

时间:2018-03-10 02:37:11

标签: mysql join left-join

我正在尝试完成我的第一次成功加入,但却无法使其正常运行。

以下是我的3个表名和列:

STORE列:id(主要),名称,类型,国家
银行列:id,货币
STORE_BANKING(中间表)列:store_id,banking_id

我有一个简单的html搜索表单,用户可以搜索与货币和/或国家/地区匹配结果的商店结果。

我收到错误:不是唯一的表/别名:'store'

也许我的Store_banking语法不正确?也许store_banking.id应该是store_banking_id?

或许我没有使用正确的联接类型?

 $query = "(
 SELECT * 
 FROM store 
 LEFT JOIN store ON banking.id=store.id
 LEFT JOIN banking ON store_banking.id = banking.id
 WHERE ('$type' IS NULL OR '$type' = '' OR type = '$type')
 AND ('$currency' IS NULL OR '$currency' = '' OR currency = '$currency') AND 
('$country' IS NULL OR '$country' = '' OR country = '$country')order by
 name)";

所以,让我们说一些搜索国家是“任何”的商店,货币是日元。日元值存储在“Banking”表中,因此我需要查询该表并将结果中包含所有商店的日元作为货币。其他值如名称,类型和国家都在商店表中,因此更容易。

2 个答案:

答案 0 :(得分:0)

假设您要搜索Currecy,Country和type。这是查询:

 SELECT * FROM Store
            LEFT JOIN STORE_BANKING SB ON Store.id=SB.store_id
            LEFT JOIN banking B ON  SB.banking_id = B.id
            WHERE 
              ('$type' IS NULL OR '$type' = '' OR Store.type = '$type')
            AND 
              ('$country' IS NULL OR '$country' = '' OR Store.country = '$country')
            And
              ('$currency' IS NULL OR '$currency' = '' OR B.currency= '$currency')
           Order by Store.name

答案 1 :(得分:0)

您收到此错误是因为您尝试加入同一个表store而未给一个声明添加别名。

您的基本查询应为:(基于假设赌场是复制粘贴拼写而且$ banking应该是指货币)

SELECT * 
 FROM store_banking 
 LEFT JOIN store ON store_banking.store_id=store.id
 LEFT JOIN banking ON store_banking.banking_id = banking.id
 WHERE ('$type' IS NULL OR '$type' = '' OR type = '$type')
 AND ('$banking' IS NULL OR '$banking' = '' OR banking.currency = '$banking') AND 
('$country' IS NULL OR '$country' = '' OR country = '$country') order by
 store.name