【问题标题】:Help with regex for commas in sql query帮助 sql 查询中逗号的正则表达式
【发布时间】:2011-04-30 04:29:16
【问题描述】:

我有一个类似的 SQL 查询:

select column1 as a, DECODE(x, 1, x1, 2, x2) as column2, 
    DECODE(y, 1, y1, 2, y2) as column3 from test

我想选择以下逗号(用**,**表示):

select a as column1 **,** DECODE(x, 1, x1, 2, x2) as column2 **,** 
    DECODE(y, 1, y1, 2, y2) as column3 from test

我为此使用/(?!(.*\))),|,(?=.*\()/gs,但你怎么能在http://gskinner.com/RegExr/ 中看到第一个DECODE 中的逗号也被选中了。我需要该正则表达式来解析此代码中使用的选择中的列:

$select = substr($sql, 6, strpos($sql, "from") - 6);
$parts = preg_split('/(?!(.*\))),|,(?=.*\()/s', $select);

$columns = array();
foreach($parts as $p) {
    @list($id, $alias) = preg_split('/( as )/', $p);
    $columns[trim($id)] = trim($alias);
}

【问题讨论】:

  • 嗯,SQL 是一种不规则语言,因为括号对可以任意嵌套。
  • 我不知道你想问什么。也许您可以改写问题,和/或提供一些示例输出?

标签: php sql regex


【解决方案1】:

试试这个:

<?php

$sql = "select a as column1, DECODE(x, 1, x1, 2, x2) as column2, DECODE(y, 1, y1, 2, y2) as column3 from test";

$select = substr($sql, 6, strpos($sql, "from") - 6);
$select .=',';
$parts = preg_split('/ as (.*?),/s', $select, NULL, PREG_SPLIT_DELIM_CAPTURE);
$columns = array();
for($i=0; $i<count($parts)-1; $i+=2) {
  $columns[trim($parts[$i])] = $parts[$i+1];
}
print_r($columns);

?>

更新:

对于更复杂的查询,您应该使用 SQL 解析器。

【讨论】:

  • 这对我的示例来说是一个很好的解决方案,但是......我的查询可以是这样的“select t.*, t.othercolumn, anothercolumn, a as column1, DECODE(x, 1, x1 , 2, x2) as column2, DECODE(y, 1, y1, 2, y2) as column3 from test t"
  • 所以你应该使用 SQL 解析器。
猜你喜欢
  • 2013-02-23
  • 2011-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-10
相关资源
最近更新 更多