我有 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
最佳答案
您可以使用 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 )
关于MYSQL显示一列中不包含特定值的组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50696301/