我的一个MySQL社区版5.1表中有一个单元格。内容始终是特定数字。如果有多个数字,则它由;
分号分隔。
例如:
| Column |
1ar8fj
99dkek;adjidk3;dajdid
divdae;dadjid;
NULL
dkadjcud;dasd;adfkvdo
dkjfakj
...
我需要创建一些代码来获取每个列值,然后将其分解为;
,然后在分割后使用每个值来执行另一个查询,并输出结果。
我知道我可以用PHP做到这一点,但我不需要把它变成一个网页,所以我想知道这是否可能用MySQL语法编写? PHP代码看起来像这样:
<?php
$result = $mysqli->query('select column from table;');
while ($row = $result->fetch_array($result)){
$id_numbers = explode($row[0],';');
foreach($id_numbers as $key => $val){
// do another query
$result2 = $mysqli->query('select * from table2 where col_val = "'.$val.'"');
while ($row2 = $result2->fetch_array($result2){
echo $row2[0].'<br>';
}
}
}
?>
这可以直接在MySQL语法中使用吗?
感谢!!!
答案 0 :(得分:2)
呼。好的。我终于得到了它的工作,但这里有一个解决方案作为存储过程,它接受一个字符串作为分隔符的输入,并在给定的表上运行,名为testtable
--Procedure: sprecursplit
--DROP PROCEDURE IF EXISTS sprecursplit;
DELIMITER |
CREATE PROCEDURE sprecursplit
(
IN delim nvarchar(255)
)
BEGIN
declare tdone tinyint unsigned default(0);
declare depth int unsigned default(1);
declare datas nvarchar(255) default('');
declare done tinyint unsigned default(0);
declare dlength int unsigned default(1);
declare hlength int unsigned default(0);
declare pos int unsigned default(1);
declare runpos int unsigned default(1);
declare slice nvarchar(255) default('');
drop table if exists allsubs;
create temporary table allsubs(id int unsigned auto_increment, val nvarchar(255), primary key (id))engine = memory;
while tdone <> 1 do
if depth <= (select count(*) from testtable) then
select t.datastring into datas from testtable t where t.id = depth limit 1;
if length(datas) > 0 then
set dlength = length(delim);
set hlength = length(datas);
set pos = 1;
set runpos = 1;
set slice = '';
set done = 0;
if hlength > 0 then
while done <> 1 do
if runpos > hlength then
set done = 1;
else
set pos = locate(delim, substring(datas from runpos));
if pos <> 1 then
if pos > 1 then
set slice = substring(datas from runpos for (pos - 1));
else
set slice = substring(datas from runpos);
end if;
insert into allsubs (val) values (slice);
end if;
if pos = 0 then
set runpos = runpos + hlength;
else
set runpos = runpos + pos + dlength - 1;
end if;
end if;
end while;
end if;
end if;
set depth = depth + 1;
else
set tdone = 1;
end if;
end while;
select * from allsubs;
drop table allsubs;
END|
DELIMITER ;