【发布时间】:2013-08-20 14:53:48
【问题描述】:
我需要像这样从“WHERE”子句中检索表的父子关系:
select ... large list of fields with aliases ...
from ... list of joined tables ...
where ((`db_name`.`catalog`.`group` = `db_name`.`catalog_group`.`iden`)
and (`db_name`.`catalog`.`iden` = `db_name`.`catalog_sub`.`parent`))
是否有一些正则表达式可以从每个条件中获取标识符?在左侧的数组 element[0] = table 中,element[1] 是右侧的表格。 Ident 的名称可以是任何名称。所以只有像 'where' 'and' '=' 这样的 sql 运算符可能是键。
任何帮助将不胜感激。
澄清
我不想通过 WHERE 子句从 WHERE 子句中获取引用。我只想要这样的参考。所以我可以看到可能有正则表达式来替换所有序列
`.`
到
.
然后用
匹配所有反引号的对` @ ` = ` @ `
默认情况下,任何可能的查询中始终存在标识符周围的反引号。默认情况下,所有字符串值都用双引号括起来。我认为这对正则表达式大师来说并不是一项复杂的任务。提前致谢。
PS 这是因为 myISAM 引擎不支持我手动强制恢复的引用。
结束于:
public function initRef($q) {
$s = strtolower($q);
// remove all string values within double quotes
$s = preg_replace('|"(\w+)"|', '', $q);
// split by 'where' clause
$arr = explode('where', $s);
if (isset($arr[1])) {
// remove all spaces and parenthesis
$s = preg_replace('/\s|\(|\}/', '', $arr[1]);
// replace `.` with .
$s = preg_replace('/(`\.`)/', '.', $s);
// replace `=` with =
$s = preg_replace("/(`=`)/", "=", $s);
// match pairs within ticks
preg_match_all('/`.*?`/', $s, $matches);
// recreate arr
$arr = array();
foreach($matches[0] as &$match) {
$match = preg_replace('/`/', '', $match); // now remove all backticks
$match = str_replace($this->db . '.', '', $match); // remove db_name
$arr[] = explode('=', $match); // split by = sign
}
$this->pairs = $arr;
} else {
$this->pairs = 0;
}
}
【问题讨论】:
-
可能有一个正则表达式(但它确实很先进,可能很难处理),但已经有 SQL 解析器。比如PHP SQL Parser(无偏好)
-
正则表达式并不是你在碰巧涉及字符串的每一个问题上挥舞的魔法棒。