日期:2014-05-16 浏览次数:21082 次
root@localhost : test 04:47:33>select * from ab; +------------+--------------+-----------------+ | product_id | product_name | product_type_id | +------------+--------------+-----------------+ | 1 | 产品A | 1,2 | | 2 | 产品B | 2,3 | +------------+--------------+-----------------+ 2 rows in set (0.00 sec) root@localhost : test 04:47:42>select * from ac; +-----------------+-------------------+ | product_type_id | product_type_name | +-----------------+-------------------+ | 1 | 类别1 | | 2 | 类别2 | | 3 | 类别3 | +-----------------+-------------------+ 3 rows in set (0.00 sec) root@localhost : test 04:47:44>select product_id,product_name,group_concat(product_type_name) as type from ab,ac where instr(ab.product_type_id,ac.product_type_id) group by product_id,product_name; +------------+--------------+-----------------+ | product_id | product_name | type | +------------+--------------+-----------------+ | 1 | 产品A | 类别1,类别2 | | 2 | 产品B | 类别2,类别3 | +------------+--------------+-----------------+ 2 rows in set (0.00 sec)
------解决方案--------------------
select product_id,product_name,ab.product_type_id,group_concat(product_type_name) as typename from ab,ac where instr(ab.product_type_id,ac.product_type_id) group by product_id,product_name; +------------+--------------+-----------------+-----------------+ | product_id | product_name | product_type_id | typename | +------------+--------------+-----------------+-----------------+ | 1 | 产品A | 1,2 | 类别1,类别2 | | 2 | 产品B | 2,3 | 类别3,类别2 | +------------+--------------+-----------------+-----------------+
------解决方案--------------------
用GROUP_CONCAT即可
------解决方案--------------------
select a.*,group_concat(b.product_type_name)
from 表1 a, 表2 b
where find_in_set(b.product_type_id, a.product_type_id)
group by a.product_id