问题描述
想象一下,我有table1
,其中有一个名为"table_name"的列.我使用table1
.table_name将另一个表的名称存储在数据库中.可引用的表都将具有字段"target_id".
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.
是否可以在JOIN语句中使用table_name?
Is is possible to use table_name in a JOIN statement?
例如:
SELECT t1.*, t2.* FROM table1 AS t1
JOIN table1.table_name AS t2 ON t1.table1_id = t2.target_id
显而易见的解决方案是使用脚本(在我的情况下为C ++)首先获取表名,然后从中构造SQL查询.问题是:我们可以绕过脚本并直接在SQL(MySQL)中执行此操作吗?
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)?
推荐答案
唯一的机会是执行2条SQL语句:
The only chance you have is to do 2 SQL statements:
- 选择所需的表名
- 使用此表名动态构建第二查询以获取所需的数据-所需的数据无法直接用SQL进行(听起来像您在某种程度上设计了错误的数据库-但不知道目标是什么很难说.
这篇关于SQL:如何在table1的字段中给定的表上建立table1 JOIN table2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!