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

标签 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

最佳答案

您可以使用 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/

相关文章:

sql - 对于特定列的每个不同值,选择除第一行之外的所有行

php - 在一定时间(30 秒)后检查 mysql 数据库中的值后运行函数

mysql - 知道一行是否有最低的列?

php - 将 mysql 数据库与 xml 文件同步

sql - 选择同一列上的两个计数

mysql - mysql中按年、月分组时出错

sql - 计算行和列中值的频率 SQL

php - 3 表之间的 Laravel Eloquent 关系

scala - 在 Spark 中连接两个具有不同记录和大小的数据框

php - 检查行是否有特定的 child 加入