简体   繁体   中英

SQL select from another table values comma separated where ids are contained in a string

I have a table:

ID | Type | Name
______________________
1  | 3   | Electronic
2  | 4   | Mechanical
3  | 6   | Other

and another table

ID | Name | Type
_____________________
1  | x5f2 | 34
2  | x5f3 | 46

What I want to do is select an entry in the second table and have it like this:

ID | Name | TypeNames
__________________________________
1  | x5f2 | Electronic, Mechanical
2  | x5f3 | Mechanical, Other

I tried using the SQL FIND_IN_SET function but I can't get the Type field from the first table separated by commas and have all of them on the same line.

SELECT table2.ID, 
       table2.Name,
       GROUP_CONCAT(table1.Name) TypeNames
FROM table1 
JOIN table2 ON LOCATE(table1.Type, table2.Type)
GROUP BY table2.ID, 
         table2.Name;

fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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