简体   繁体   中英

How to convert string value separated by comma into integer from mySQL

I am working on a php project to retrieve data from mysql. I have a list of codes that is stored as a string separated by commas that is referenced in another table. Is there a way to get all the value from the string and return the text it referenced?

For example, item_purchased might contain one or more than one item_code. I want the query to return item names instead of item codes.

//item_purchased for transaction 123 --> ,111,222,333,

SELECT s.transaction_id, s.item_purchased, i.item_id
FROM stock s

INNER JOIN ref_item i
ON s.item_code = i.item_code

WHERE transaction_id = 123

Desired outcome: apple, carrot, milk (not ,111,222,333,)

Is there a way to do this preferably within mySQL query or maybe in PHP?

This is one of the reasons why you shouldn't use comma-separated lists in relational databases .

The workaround is to use the FIND_IN_SET() function in the join conditions, instead of = .

SELECT s.transaction_id, GROUP_CONCAT(i.item_name)
FROM stock s

INNER JOIN ref_item i
ON FIND_IN_SET(i.item_code, s.item_purchased)

WHERE s.transaction_id = 123

GROUP BY s.transaction_id

But unfortunately, this makes the query very inefficient, because it can't use an index to search the ref_item table. It has to do a table-scan, so it ends up having very poor performance, and gets much worse the larger your table gets.

Is item_purchased a comma separated string of item_code? I'm not good with joins but I think this will do

SELECT s.transaction_id, s.item_purchased, DISTINCT(i.item_id)
  FROM stock s, ref_item i
 WHERE i.item_code in (s.item_purchased ) 
   AND s.transaction_id = 123

This will return a list of all the items in the item_purchased column if my assumption of the item_purchase is right.

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