简体   繁体   中英

create list from a comma separated key in mysql

I have data set like this in MySQL:

table order
order_id   item_id        
1          A,B,C
2          B,D,E

and

table item 
item_id    item_name
A          Candy
B          Beer
C          Cookies
D          Jam
E          Cigarette

How can I return data like this:

order_id   item_id    item_name
1          A,B,C      Candy,Beer,Cookies
2          B,D,E      Beer,Cookies,Cigarette

You can try below query-

SELECT o.order_id, o.item_id, GROUP_CONCAT(itm.item_name) 
FROM `order` AS o JOIN item AS itm ON FIND_IN_SET(itm.item_id,o.item_id) 
GROUP BY o.order_id;

Try This...

select o.order_id, o.item_id, GROUP_CONCAT(i.item_name SEPERATOR separator ',')
FROM order o
INNER JOIN item i ON on (find_in_set(i.item_id,o.item_id))
GROUP BY o.order_id

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