简体   繁体   English

在MySQL中使用连接两个表以逗号分隔的ID来获取值

[英]To fetch value with comma separated ID with Join two tables in MySQL

I have 2 tables shown as below 我有2张桌子,如下所示

product_category Table product_category表

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

product_category_description Table product_category_description表

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

I want output shown below 我想要下面显示的输出

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

I have tried below query but not working: 我已经在下面的查询中尝试过,但是无法正常工作:

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

Everthing is right except the group by field 除按字段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

Use below query i checked with my database 使用下面的查询我检查了我的数据库

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM