這樣的遞迴怎麼做?!
select a,
(select b from c where ...) as d,
e
from f,(select j from h where ...) as i
where ....
我要把外層select ... from ...中,select後面的內容替換掉,而保留from後面的內容。最後變成:
select count(*)
from f,(select j from h where ...) as i
where ....
其實這相當於xml/html節點的替換,類似遞迴問題,想了很久也沒想到解決方案。
------解決方案--------------------
正則....不行
如果你只是想得到返回的行數, 你總是可以這樣做:
select count(*) from (
-- 你的sql --
select a,
(select b from c where ...) as d,
e
from f,(select j from h where ...) as i
where ....
) tmp
如果你非要嚴格做替換, 要做文法分析, 考慮到單雙引號, 括弧等等....
------解決方案--------------------
不知道你是要寫SQL指令,還是要做字串替換
如果是做字串替換,可以這麼寫
$s = <<< TXT
select a,
(select b from c where ...) as d,
e
from f,(select j from h where ...) as i
where ....
TXT;
$ar = preg_split('/(\(?\bselect\b
------解決方案--------------------
\bfrom\b)/i', $s, -1, PREG_SPLIT_NO_EMPTY
------解決方案--------------------
PREG_SPLIT_DELIM_CAPTURE);
$n = 0;
$st = array();
for($i=0; $i $t = strtolower($ar[$i]);
if($t == 'select'
------解決方案--------------------
$t == '(select') {
$st[] = $i;
}
if($t == 'from') {
if(count($st) == 1) break;
array_pop($st);
}
}
for($i--; $i>$st[0]+1; $i--) unset($ar[$i]);
$ar[$st[0]+1] = " count(*)\n";
echo join('', $ar);
select count(*)
from f,(select j from h where ...) as i
where ....