MYSQL显示在一列中不包含特定值的组

时间:2018-06-05 09:09:19

标签: mysql join group-by

我有2张表customer_address_entity

entity_id | foo | bar
----------------------
1         | bla | bla
2         | bla | bla
3         | bla | bla

customer_address_entity_varchar

value_id | attribute_id |entity_id | value
-------------------------------------------------
1        | 21           | 1        | something_1
2        | 22           | 1        | anything_1
3        | 31           | 1        | whatever_1
4        | 21           | 2        | something_2
5        | 22           | 2        | anything_2
6        | 21           | 3        | something_3
7        | 31           | 3        | whatever_3

我想在customer_address_entity中选择customer_address_entity_varchar中没有任何attribute_id = 31值的所有元素。

例如,customer_address_entity entity_id = 2的customer_address_entity_varchar attribute_id值为21和22但不是31.所以我想选择这个。

刚才我加入了两个表,并按entity_id对它们进行分组,但是

SELECT cae.`entity_id`, caev.`attribute_id`, caev.`value`
FROM `customer_address_entity` AS `cae`
INNER JOIN `customer_address_entity_varchar` AS `caev`
ON cae.`entity_id`=caev.`entity_id`
GROUP BY cae.`entity_id`;

使用GROUP_BY连接表的示例:

entity_id | attribute_id | value
---------------------------------------
1         | 21           | something_1
2         | 21           | something_2
3         | 21           | something_3

我被困在这里,因为我不知道如何在attribute_id中选择没有31的组。

期望的结果:

entity_id | attribute_id | value
---------------------------------------
2         | 21           | something_2

3 个答案:

答案 0 :(得分:2)

一种选择是使用聚合来查找匹配的组:

SELECT t1.entity_id, t1.attribute_id, t1.value
FROM customer_address_entity_varchar t1
INNER JOIN
(
    SELECT entity_id
    FROM customer_address_entity_varchar
    GROUP BY entity_id
    HAVING SUM(CASE WHEN attribute_id = 31 THEN 1 ELSE 0 END) = 0
) t2
    ON t1.entity_id = t2.entity_id;

如果您不想要customer_address_entity_varchar表中的完整匹配记录,而只需要entity_id值,那么只需将上面的子查询别名用作t2。< / p>

答案 1 :(得分:2)

您可以使用not exists子句实现所需的结果。尝试以下查询,它检查属性id = 31的每个实体id。

SELECT * 
FROM customer_address_entity_varchar t1
WHERE 
NOT EXISTS (SELECT 1 FROM customer_address_entity_varchar t2 WHERE t1.entity_id = t2.entity_id
and attribute_id = 31  ) 

答案 2 :(得分:2)

SELECT cae.`entity_id`, caev.`attribute_id`, caev.`value`
FROM `customer_address_entity` AS `cae`
INNER JOIN `customer_address_entity_varchar` AS `caev`
ON cae.`entity_id`=caev.`entity_id`
where cae.entity_id not in (select caev2.entity_id  from `customer_address_entity_varchar` AS `caev2` where caev2.attribute_id = 31)

您需要从第一个查询中删除所有entity_id,其中包含attribute_id = 31