如何返回数据库中所有表的列表,其中主机名列包含 hostname=hostA
我可以使用以下方法获取包含“主机名”列的所有表:
select select table_name from information_schema.columns
where column_name='hostname';
如果我知道所有表的名称,我可以使用像这样的联合:
SELECT * FROM ((SELECT hostname FROM table1)
UNION (SELECT hostname FROM table2)
...
UNION (SELECT hostname FROM tableN)) AS hosttable where hostname = 'hostA';
但我不知道如何在不使用外部脚本或存储过程的情况下组合上述两个概念。
I can get all the tables containing column 'hostname' using:
select select table_name from information_schema.columns
where column_name='hostname';
If I knew the names of all the tables I could use a union like:
SELECT * FROM ((SELECT hostname FROM table1)
UNION (SELECT hostname FROM table2)
...
UNION (SELECT hostname FROM tableN)) AS hosttable where hostname = 'hostA';
But I don't know how to combine the above two concepts without using an external script or stored procedure.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
SQL 查询必须显式列出表和列。您无法编写从同一查询中搜索的另一列的结果中获取表名称的查询。
解决方案是您已经找到的解决方案:针对信息模式编写一个 SQL 查询以获取表名列表,然后使用这些结果构建第二个 SQL 查询,将表名插入到查询中的适当位置。
您可以使用
PREPARE
和EXECUTE
在存储过程中执行此操作,也可以在应用程序代码中执行此操作。SQL queries must list the tables and columns explicitly. You can't write a query that takes the name of a table from the result of another column searched in the same query.
The solution is the one you have already found: write one SQL query against the information schema to get a list of table names, and then use those results to build a second SQL query, interpolating the table names into the appropriate place in the query.
You can do this in a stored procedure with
PREPARE
andEXECUTE
, or you can do it in application code.