左连接相同的表但具有不同的值?

时间:2012-07-30 22:08:21

标签: mysql

Table_A entity_id

Table_B 有一个相关的 entity_id attribute_id = 1

Table_B 有一个相关的 entity_id attribute_id = 2

  SELECT Table_B.value
    FROM  Table_A
    LEFT JOIN Table_B
    ON Table_A.entity_id = Table_B.entity_id
    WHERE Table_A.date =  '2012-7-30 00:00:00'
    AND Table_B.attribute_id = 1

我想将attribute_id = 1和attribute_id = 2纳入一个查询。

3 个答案:

答案 0 :(得分:1)

您可以第二次加入Table_B并使用AS为其命名(别名)。

SELECT Table_B.value, Table_B2.value
FROM  Table_A
LEFT JOIN Table_B
ON Table_A.entity_id = Table_B.entity_id
LEFT JOIN Table_B AS Table_B2
ON Table_A.entity_id = Table_B2.entity_id
WHERE Table_A.date =  '2012-7-30 00:00:00'
AND Table_B.attribute_id = 1
AND Table_B2.attribute_id = 2

您还可以移动属性条件,使其更加清晰:

SELECT Table_B.value, Table_B2.value
FROM  Table_A
LEFT JOIN Table_B
ON Table_A.entity_id = Table_B.entity_id AND Table_B.attribute_id = 1
LEFT JOIN Table_B AS Table_B2
ON Table_A.entity_id = Table_B2.entity_id AND Table_B2.attribute_id = 2
WHERE Table_A.date =  '2012-7-30 00:00:00'

答案 1 :(得分:1)

嗯,你可以通过两种简单的方式来做到这一点

select 
    t1.entity_id,
    t2.attribute
from t1
left join t2 on t2.entity_id = t1.entity_id;

OR

select 
    t1.entity_id,
    group_concat(t2.attribute) as Attr
from t1
left join t2 on t2.entity_id = t1.entity_id
group by t1.entity_id

答案 2 :(得分:0)

如果你想同时获得attribute_id = 1和2,你为什么不使用OR?

SELECT Table_B.value
FROM  Table_A
LEFT JOIN Table_B
ON Table_A.entity_id = Table_B.entity_id
WHERE Table_A.date =  '2012-7-30 00:00:00'
AND (Table_B.attribute_id = 1 OR Table_B.attribute_id = 2)