【问题标题】:Trouble joining 3 tables (getting not unique table/alias)无法加入 3 个表(获取不唯一的表/别名)
【发布时间】:2018-03-10 02:37:11
【问题描述】:

我正在尝试完成我的第一次成功加入,但无法成功。

这是我的 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)";

假设一些搜索国家为“任何”且货币为日元的商店。日元值存储在“银行”表中,因此我需要查询来检查该表并在结果中包含与日元作为货币匹配的所有商店。名称、类型和国家/地区等其他值都在 Stores 表中,这样更容易。

【问题讨论】:

  • 您的查询毫无意义。表别名到处都是,表名与问题中的不同。
  • 您的“FROM”行有错字,应该简单地读为FROM store_banking
  • 我在您的架构中看不到列(类型、国家/地区...)!
  • 类型和国家在 STORE 表中。
  • 我希望它只是一张桌子,但货币被分解到银行表中,所以如果有人选择货币类型,我无法让搜索代码也返回结果

标签: mysql join left-join


【解决方案1】:

假设您要搜索货币、国家和类型。这是查询:

 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

【讨论】:

    【解决方案2】:

    您收到此错误是因为您试图加入同一个表 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
    

    【讨论】:

    • 很好地抓住了“赌场”复制粘贴错误。在我成功实施上面看到的第一个答案之前,我确实纠正了这一点。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 2019-04-28
    • 1970-01-01
    相关资源
    最近更新 更多