SET @sql:= (SELECT CONCAT('
SELECT
item,
rate,
sum_rate,
rnd
FROM (
SELECT
gacha_id,
elt(n,',group_concat(CASE WHEN type=1 THEN col ELSE '' END SEPARATOR ''),') item,
@rate:=elt(n,',group_concat(CASE WHEN type=2 THEN col ELSE '' END SEPARATOR ''),') rate,
@sum_rate:=@sum_rate+@rate sum_rate,
rnd
FROM
gacha,
(',group_concat(CASE WHEN type=1 THEN vt ELSE '' END SEPARATOR ''),') as t,
(SELECT @rate:=0,@sum_rate:=0,FLOOR(rand()*100) rnd) as v
WHERE
gacha_id = 1
) t2
WHERE
sum_rate > rnd
LIMIT 1
')
FROM (
SELECT
group_concat(column_name order by column_name SEPARATOR ',') col,
CONCAT('SELECT ',group_concat(CONCAT(REPLACE(REPLACE(column_name,'item',''),'rate',''),' as n') order by column_name SEPARATOR ' UNION ALL SELECT ')) vt,
case
when column_name like 'item%' then 1
when column_name like 'rate%' then 2
end type
FROM
information_schema.columns
WHERE
table_schema = 'test'
AND
table_name = 'gacha'
AND
(
column_name like 'item%'
OR
column_name like 'rate%'
)
GROUP BY
case
when column_name like 'item%' then 1
when column_name like 'rate%' then 2
end
) t
);
PREPARE dynamic_sql FROM @sql;
EXECUTE dynamic_sql;