MySQL - 显示两列,其中第一列值在表 C 中,第二列值不在表 C 中

标签 mysql

假设有两个表:must_have_products 和 products_buyed 我想为每个客户展示他们已经拥有的产品 已购买为 col A (GROUP_CONCAT),他们仍需要购买哪些产品为 col B (GROUP_CONCAT)..

Table A(must_have_products)
|id_a| name  |
|1a  | TV    |
|2a  | House |
|3a  | Car   |

Table B(People)
|id_b| name  |
|1b  | Mr. A |
|2b  | Mr. B |

Table C
|id_c|id_b|id_a|
|1   |1b  |1a  |

预期结果:

|id_b  | buyed  | left       |
|1b    | 1a     | 2a, 3a     |
|2b    |        | 1a, 2a, 3a |

PS:如果标题有误,我很抱歉,我不知道该说什么

最佳答案

这里有一个方法可以做到这一点。获取使用 group_concat 购买的元素很容易,但没有购买的元素并不直接。

select
t2.id_b,
group_concat(t1.id_a) as buyed,
case 
when group_concat(t1.id_a) is null 
then (select group_concat(id_a order by id_a) from tableA) 
else substring_index((select group_concat(id_a order by id_a) from tableA),
concat(group_concat(t1.id_a order by t1.id_a),','),-1)
end as `left`
from tableB t2
left join tableC t3 on t3.id_b = t2.id_b
left join tableA t1 on t1.id_a = t3.id_a
group by t2.id_b

DEMO

关于MySQL - 显示两列,其中第一列值在表 C 中,第二列值不在表 C 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27467134/

相关文章:

MySQL 查询两行为一

mysql - Homebrew 在尝试安装 mysql 时说 "Warning: mysql-5.6.13 already installed",但在本地 gems 中不可见

php - 计算不同表的平均值

mysql - Loopback 中基于用户的动态数据库连接

php - 在一张表中插入会自动将 null 添加到另一张表中

mysql - 查询多对多链接表

php - 从mysql上的两个表中选择

php - 通过 html 表单和 php 将外国 lang 数据插入 mysql db 表

mysql - 无法连接到AWS ECS上的MySQL容器

mysql - 是否可以在进行 SQL 查询的同时进行身份验证(不预先进行身份验证)