MySQL加入问题

时间:2011-02-25 21:46:23

标签: mysql left-join

编辑2:
在这里找不到任何东西,在其他地方找不到它。
谁知道!= NULL在MySQL中不起作用 主持人请删除这个吗?

我有一个eav数据库,我需要从中选择一些带有属性的产品 当我使用

select attribute1.value as a1, attribute2.value as a2, products.id
from attributes attribute1, attributes attribute2, products
where product.id = attribute1.product_id and attribute1.name = 'abc' and
    product.id = attribute2.product_id and attribute2.name = 'def'

如果某个产品缺少某个属性,我就无法获取所有产品,如果缺少属性,我需要使用NULL获取所有产品。
当我使用

select attribute1.value as a1, attribute2.value as a2, products.id
from products
left join attributes as attribute1 on (product.id = attribute1.product_id and attribute1.name = 'abc')
left join attributes as attribute2 on (product.id = attribute2.product_id and attribute2.name = 'def')

我得到了所有产品,但所有产品都有a1 = NULL,即使在数据库中也没有。{ 有什么问题?

示例:

产品:

 id
1000
1001
1002
1003

属性:

name    product_id    value
abc        1000         1
abc        1002         2
def        1000         3
def        1001         4

预期结果:

 id     a1      a2
1000    1       3
1001   NULL     4
1002    2      NULL
1003   NULL    NULL

第一次查询的结果:

 id     a1      a2
1000    1       3

第二次查询的结果:

 id     a1      a2
1000   NULL     3
1001   NULL     4
1002   NULL    NULL
1003   NULL    NULL

编辑:

修正了第二个查询和示例。

3 个答案:

答案 0 :(得分:1)

有几个问题:

  1. 您缺少from子句来启动查询
  2. 您需要为attribute.name测试使用正确的表别名,特别是attribute1.nameattribute2.name
  3. 以这种方式尝试:

    select attribute1.value as a1, attribute2.value as a2, products.id
        from products
            left join attributes as attribute1 
                on products.id = attribute1.product_id 
                    and attribute1.name = 'abc'
            left join attributes as attribute2 
                on products.id = attribute2.product_id 
                    and attribute2.name = 'def'
    

答案 1 :(得分:0)

查询

select attribute1.value as a1, attribute2.value as a2, products.id
left join attributes as attribute1 on (product.id = attribute1.product_id and attribute.name = 'abc')
left join attributes as attribute2 on (product.id = attribute2.product_id and attribute.name = 'def')

不对,哪里有产品表?

还有什么是attribute.name,你没有名字/别名属性的表

答案 2 :(得分:0)

为了使它工作,你必须用FROM替换第一个JOIN,如下所示:

SELECT attribute1.value AS a1, attribute2.value AS a2, products.id
FROM attributes AS attribute1 ON (product.id = attribute1.product_id AND attribute.name = 'abc')
LEFT JOIN attributes AS attribute2 ON (product.id = attribute2.product_id AND attribute.name = 'def')