简体   繁体   English

如何将逗号分隔的字符串值从 mySQL 转换为整数

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

I am working on a php project to retrieve data from mysql.我正在开发一个从 mysql 检索数据的 php 项目。 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.例如,item_purchased 可能包含一个或多个 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?有没有办法最好在 mySQL 查询中或在 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 = .解决方法是在连接条件中使用FIND_IN_SET() 函数,而不是=

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.但不幸的是,这使得查询效率非常低,因为它无法使用索引来搜索 ref_item 表。 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? item_purchased是逗号分隔的 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.如果我对 item_purchase 的假设是正确的,这将返回item_purchased列中所有项目的列表。

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

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