SQL:我们如何在 table1 的字段中给定的表上创建 table1 JOIN table2 ?
假设我有 table1
,其中有一列名为“table_name”。我使用 table1
.table_name 来存储数据库中另一个表的名称。可引用的表都有一个字段“target_id”。
可以在 JOIN 语句中使用 table_name 吗?
例如:
SELECT t1.*, t2.* FROM table1 AS t1
JOIN table1.table_name AS t2 ON t1.table1_id = t2.target_id
显而易见的解决方案是使用脚本(在我的例子中是 C++)首先获取表名,然后从中构造一个 SQL 查询。问题是:我们可以绕过脚本并直接在 SQL (MySQL) 中执行此操作吗?
编辑:什么是动态 SQL?
Imagine I have table1
which has a column named 'table_name'. I use table1
.table_name to store the name of another table in the database. The referenceable tables would all have a field 'target_id.
Is is possible to use table_name in a JOIN statement?
For example:
SELECT t1.*, t2.* FROM table1 AS t1
JOIN table1.table_name AS t2 ON t1.table1_id = t2.target_id
The obvious solution is to use the script (C++ in my case) to get the table name first, and construct a SQL query from it. The question is: can we bypass the script and do this directly in SQL (MySQL)?
Edit: What is dynamic SQL?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你唯一的机会是执行 2 个 SQL 语句:
The only chance you have is to do 2 SQL statements:
我知道我参加聚会迟到了,但我想提供不同的解决方案。我在审计表中经常看到这种事情。
table_name
列指的是“更改了什么表”,table1_id
指的是该表中发生更改的行的 ID。在这种情况下,审计表指向许多通常不会连接的不同表。当然
,主要缺点是每个可能引用的表都需要显式包含在 SQL 命令中。
您可以使用它作为您的选择列表来获得更优雅的输出:
等等
I know I'm late to the party, but I wanted to offer a different solution. I see this sort of thing a lot in audit tables. The column
table_name
would refer to "what table was changed" andtable1_id
would refer to the ID of the row that changed in that table. In this case, the audit table is pointing back to many different tables that don't normally get joined.Here goes:
Of course, the main drawback is that each table that can be possibly referenced needs to be explicitly included in the SQL command.
You can get more elegant output using this as your select list:
etc