我需要在mysql的视图中使用的表列表。 例如,如果我有一个类似的视图:
SELECT * FROM table1
JOIN table2
ON table1.id = table2.id
我想得到:table1,table2
答案 0 :(得分:1)
mysql> CREATE VIEW vw_test AS
-> SELECT * FROM table1 JOIN table2 ON table1.id = table2.id;
Query OK, 0 rows affected (0.00 sec)
mysql> SELECT VIEW_DEFINITION FROM INFORMATION_SCHEMA.VIEWS
-> WHERE TABLE_NAME = 'vw_test';
+------------------------------------------------------------------+
| VIEW_DEFINITION |
+------------------------------------------------------------------+
| select * from table1 join table2 on table1.id = table2.id; |
+------------------------------------------------------------------+
1 row in set (0.00 sec)
然后您可以使用以下任何工具来解析表名:
Terence Parr的ANTLR解析器生成器(Java,但可以使用多种目标语言中的任何一种生成解析器)有几种可用的SQL语法,包括一对用于PL / SQL,一种用于SQL Server SELECT语句,一个用于mySQL,一个用于ISO SQL - (http://www.antlr.org/grammar/list)。
我从这里回答:SQL parser library for Java - Retrieve the list of table names present in a SQL statement
Data Tools Project - SQL Development Tools(http://www.eclipse.org/datatools/project_sqldevtools/)。
以下是SQL Query Parser(http://www.eclipse.org/datatools/project_sqldevtools/sqltools_doc/SQL%20Query%20Parser%20User%20documentation.htm)的文档。
或者根据以下内容编写自定义mySQL proc(在此处找到 - http://www.sqlparser.com/fetch-table-column-name-example-extact-all-table-field-name.php):
SELECT c_mandant, hist_datum, parkey1, parkey2, funktionscode, ma_parkey, me_parkey
, CASE WHEN EXISTS (SELECT 1
FROM CDS_H_GRUPPE GRP1
WHERE GRP1.c_mandant = c_mandant
AND GRP1.hist_datum = ADD_MONTHS(LAST_DAY(TRUNC(SYSDATE)), -1)
AND GRP1.funktionscode = 'H'
AND GRP1.parkey1 = ma_parkey)
THEN 1
ELSE NULL
END MA_ME
, CASE WHEN EXISTS (SELECT 1
FROM CDS_H_GRUPPE GRP2
WHERE GRP2.c_mandant = c_mandant
AND GRP2.hist_datum = ADD_MONTHS(LAST_DAY(TRUNC(SYSDATE)), -1)
AND GRP2.funktionscode = 'U'
AND GRP2.parkey1 = me_parkey)
THEN 1
ELSE NULL
END ME_MA
, ROW_NUMBER() OVER (PARTITION BY c_mandant, ma_parkey, me_parkey ORDER BY c_mandant, ma_parkey, me_parkey) ANZ_MA
FROM (SELECT c_mandant, hist_datum, parkey1, parkey2, funktionscode
, CASE WHEN funktionscode = 'U'
THEN parkey1
ELSE parkey2
END MA_PARKEY
, CASE WHEN funktionscode = 'U'
THEN NULL
ELSE parkey1
END ME_PARKEY
FROM
CDS_H_GRUPPE
WHERE
funktionscode IN ('U', 'H')
AND hist_datum = ADD_MONTHS(LAST_DAY(TRUNC(SYSDATE)), -1)
)
答案 1 :(得分:0)
不幸的是,我不相信这是可能的。相反,您需要查询和解析实际的视图定义:
SELECT VIEW_DEFINITION
FROM INFORMATION_SCHEMA.VIEWS
WHERE
TABLE_NAME = ?;
答案 2 :(得分:0)
否这是不可能的。您必须查找视图的定义并手动完成。
答案 3 :(得分:0)
这就是您想要的...这可以使Views中使用的表和联接在一起的表..但是它可以得到一个联接...如果要更多,则添加更多提示。.
希望这可以解决您的问题...
select
case
when view_definition regexp '.*from +.*'
then substring_index(substring_index(view_definition, 'from ', -1), ' ', 1)
end as 'primary table',
case
when view_definition regexp '.*join +.*'
then substring_index(substring_index(view_definition, 'join ', -1), ' ', 1)
end as 'joined table'
from information_schema.views where table_name="YOUR VIEW NAME" and table_schema="shotbot_production";