需要有关正则表达式的帮助来提取sql子查询

时间:2012-11-28 09:30:45

标签: regex

我是regx的新手...我希望使用正则表达式从给定查询中获取子查询。

例如,我有如下的查询

Select * from (
   select * from Table_A where ID = 90 
   UNION 
   select * from Table_B where ID = 90
)  as SUBQUERY left join TABL_ABC abc ON (abc.id = SUBQUERY.id)

现在我希望我的正则表达式仅匹配以下行:

select * from Table_A where ID = 90 
   UNION 
   select * from Table_B where ID = 90

请帮助我,提前谢谢你......

2 个答案:

答案 0 :(得分:0)

如果它是一个没有额外大括号的简单子查询,你可以使用这个正则表达式

/\(\s*(select[^)]+)\)/i

答案 1 :(得分:0)

<?php
$sql = 'Select * from ( select * from Table_A where ID = 90 UNION select * from Table_B where ID = 90 ) as SUBQUERY left join TABL_ABC abc ON (abc.id = SUBQUERY.id)';

if( preg_match('/\(\s*(select.+)\) as /iU', $sql, $matched ) ){
    $subquery = trim( $matched[1] );
    var_dump( $subquery );   
}