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