SQL不同的关节和WHERE子句可能是错误的

时间:2013-06-27 15:32:27

标签: mysql sql join left-join

以下是我的表格:

auth_keys

id    /    keys    / user 
1     /    12345   /   1

* 产品*

id    / company    /   name
1     /  1         /   iphone
2     /  2         /   iphone

公司

id    / name       /   mkey
1     / myComp     /   54321

这是我的sql请求:

SELECT 
    products.id_product AS id_product, 
    auth_keys.keys AS vkey,
    auth_keys.user AS user_id
FROM 
    auth_keys
JOIN 
    products
LEFT JOIN 
    companies ON products.company = companies.id
WHERE 
    products.name_product = "iphone"
    AND companies.mkey = "54321" 
HAVING 
    vkey = "none"

我想做的事情:

  • id_products获得id_company然后获得name_product,因为我可以为两家不同的公司提供同名产品。这部分没问题。

  • 我想要user_keyWHERE keys = "12345" OR "NONE",这就是我的问题。如果keys =“12345”,一切都有效,但如果key =“none / nothing”,我什么也得不到......

我想得到第一个结果,id_product,即使我无法匹配user_key ...

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

试试这个:


    SELECT 
    products.id_product AS id_product, 
    auth_keys.keys AS vkey,
    auth_keys.user AS user_id
    FROM auth_keys
    JOIN products
    LEFT JOIN companies ON products.company = companies.id
    WHERE 
    products.name_product = "iphone"
    AND (companies.mkey = "54321"or vkey = "none")

不需要与“group by”子句一起使用的“having”来过滤聚合结果。

答案 1 :(得分:0)

我真的很难理解表格如何结合在一起。您似乎希望在没有任何条件的情况下加入auth_keys,除非密钥必须是12345或NONE。如果两者都匹配,不确定你想要什么。

然而快速尝试

SELECT products.id_product AS id_product, 
    auth_keys.keys AS vkey,
    auth_keys.user AS user_id
FROM products
LEFT OUTER JOIN companies
ON products.company = companies.id
AND companies.mkey = "54321"
LEFT OUTER JOIN auth_keys
ON auth_keys.keys IN ('12345', 'NONE')
WHERE products.name_product = "iphone"