让我们说有两个表: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:对不起,如果标题错了,我只是不知道该说什么
答案 0 :(得分:2)
这是一种方法。使用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 强>
答案 1 :(得分:1)
left是关键字,您无法使用它mysql-left-function
这是解决方案:
select B.id_b, COALESCE(R1.buyer, '') buyer, COALESCE(R2.lft, '') lft
from
B,
(select B.id_b , GROUP_CONCAT(DISTINCT A2.id_a SEPARATOR ', ') as buyer
from B
left join A A2
on Exists(select * from C where A2.id_a = C.id_a and C.id_b = B.id_b)
group by B.id_b
) R1,
(
select B.id_b , GROUP_CONCAT(DISTINCT A2.id_a SEPARATOR ', ') as `left`
from B
left join A A2 on
NOT Exists(select * from C where A2.id_a = C.id_a and C.id_b = B.id_b)
group by B.id_b
) R2
where
B.id_b = R1.id_b and B.id_b = R2.id_b