提取sql中涉及到的表名?
请问ruby中如何获取到一条sql中涉及到的所有表
比如sql是 select * from users结果是 users
简单的用正则可以匹配,但是复杂的好像匹配不了在mysql层面有啥语句会查询得到吗
看了explain,里面好像没有列举出涉及到的表名
回复
1个回答

test
2024-09-07
https://github.com/greenlion/PHP-SQL-Parser 可以用这个解析
SELECT a, b, c
FROM some_table an_alias
JOIN `another` AS `another table` USING(id)
WHERE d > 5
输出结果:
Array
(
[SELECT] => Array
(
[0] => Array
(
[expr_type] => colref
[base_expr] => a
[sub_tree] =>
)
[1] => Array
(
[expr_type] => colref
[base_expr] => b
[sub_tree] =>
)
[2] => Array
(
[expr_type] => colref
[base_expr] => c
[sub_tree] =>
)
)
[FROM] => Array
(
[0] => Array
(
[expr_type] => table
[table] => some_table
[alias] => Array
(
[as] =>
[name] => an_alias
)
[join_type] =>
[ref_type] =>
[ref_clause] =>
[base_expr] => some_table
[sub_tree] =>
)
)
[JOIN] => Array
(
[0] => Array
(
[expr_type] => table
[table] => another
[alias] => Array
(
[as] => AS
[name] => another table
)
[join_type] => JOIN
[ref_type] => USING
[ref_clause] => Array
(
[0] => Array
(
[expr_type] => colref
[base_expr] => id
[sub_tree] =>
)
)
[base_expr] => JOIN `another` AS `another table` USING(id)
[sub_tree] =>
)
)
[WHERE] => Array
(
[0] => Array
(
[expr_type] => colref
[base_expr] => d
[sub_tree] =>
)
[1] => Array
(
[expr_type] => operator
[base_expr] => >
[sub_tree] =>
)
[2] => Array
(
[expr_type] => const
[base_expr] => 5
[sub_tree] =>
)
)
)
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容