使用逗号分隔ID获取值,并在MySQL中使用Join两个表

时间:2014-10-14 11:05:34

标签: php mysql

我有2个表格如下所示

product_category表

╔═════════════╦═════════════════╗
║ category_id ║    parent_id    ║
╠═════════════╬═════════════════╣
║ 1           ║ 8,7             ║
║ 2           ║ 8               ║
╚═════════════╩═════════════════╝

product_category_description表

╔═════════╦═══════════╦═════════╗
║ id      ║category_id║ name    ║
╠═════════╬═══════════╬═════════╣
║ 1       ║   1       ║ Test    ║
║ 2       ║   2       ║ Test1   ║
║ 3       ║   3       ║ Test2   ║
║ 4       ║   7       ║ Test3   ║
║ 5       ║   8       ║ Test4   ║
╚═════════╩═══════════╩═════════╝

我想要输出如下所示

    ╠══════════╬═══════════════╣
    ║ 1        ║ Test4, Test3  ║
    ║ 2        ║ Test4         ║
    ╚══════════╩═══════════════╝

我尝试过以下查询但没有工作:

SELECT GROUP_CONCAT(b.category_name) cat_name 
FROM  product_category  a 
INNER JOIN product_category_description b 
ON FIND_IN_SET(a.parent_id, b.category_id) > 0 
GROUP   BY b.category_id

2 个答案:

答案 0 :(得分:2)

group by字段

外,一切正常
SELECT GROUP_CONCAT(b.category_name) cat_name 
FROM  
product_category  a 
INNER JOIN 
product_category_description b 
ON FIND_IN_SET(a.parent_id, b.category_id) > 0 
GROUP BY 
a.category_id

答案 1 :(得分:2)

使用以下查询我用我的数据库检查

SELECT a.category_id,GROUP_CONCAT(DISTINCT b.name)
FROM product_category_description  AS b
INNER JOIN `product_category` as a 
ON  FIND_IN_SET(b.category_id,a.parent_id)
GROUP BY category_id