sql 循环遍历字符串并将其字符输入到 select 的过程

sql procedure to loop through string and input its characters to select

有没有一种方法可以在 sql 中创建能够产生以下内容的过程:

SET @teststr = '(1, 2, 3)';
select sum(products_storage.product_price)
from (select 1 as id union all
      select 2 as id union all
      select 3 as id
     ) i join products_storage
        query_products_in_stock

而不是手动 select 部分,有没有办法循环遍历 teststr 字符串和 select 来自它的每个 ID 并得到相同的结果?

这适用于 Mysql5.5+

SET @teststr = '1, 2, 3';


SELECT
  SUBSTRING_INDEX(SUBSTRING_INDEX(tablename.name, ',', numbers.n), ',', -1) name
FROM
  (SELECT 1 n UNION ALL SELECT 2
   UNION ALL SELECT 3 UNION ALL SELECT 4) numbers INNER JOIN (select @teststr name from dual) tablename
  ON CHAR_LENGTH(tablename.name)
     -CHAR_LENGTH(REPLACE(tablename.name, ',', ''))>=numbers.n-1
ORDER BY
   n;

我想你问的是 find_in_set():

select sum(products_storage.product_price)
from query_products_in_stock qpin
where find_in_set(qpin.id, replace(replace(replace(@testtr, ', ', ','), '(', ''), ')', '')

当然,如果字符串表示为:

,这会更简单
SET @teststr = '1,2,3';

这就引出了一个问题,即为什么您不将查询指定为:

select sum(products_storage.product_price)
from query_products_in_stock qpin
where qpin.id like (1, 2, 3);