SQL 从列中描述的表名中进行选择



我想从一个sql表中进行选择,该表的表名在另一个表中描述。

SELECT * 
FROM first_table t1 
WHERE EXISTS (SELECT * FROM t1.other_table t2 WHERE t1.other_table_id = t2.id)

找不到解决方案!

感谢任何帮助。

解决方案

您可以将动态变量与查询一起使用:

SET @table := (select tableName from test limit 1);
set @qry1:= concat('select * from ',@table);
prepare stmt from @qry1 ;
execute stmt ;

甚至

set @qry1:= concat('select * from ', (select tableName from test limit 1));
select @qry1;
prepare stmt from @qry1 ;
execute stmt ;

SQLFiddle 示例:http://sqlfiddle.com/#!9/a787e3/1

注意:SqlFiddle 不允许在右侧编辑器中运行execute,所以我不得不使用视图。

免责声明/注释:

您应该清理表名称表的所有输入。这样就不会有人将 SQL 插入到此表中并执行它。

此外,请注意,在真实的数据库中,我们将对表选择查询有一个where条件。

例:

set @qry1:= concat('select * from ', (select tableName from test where id='something'));
SELECT * 
FROM first_table t1 
WHERE EXISTS (SELECT * FROM other_table t2 WHERE t1.other_table_id = t2.id)
mysql> SELECT @other_table := other_table FROM first_table WHERE 1 = 1;
mysql> SET @s = CONCAT("SELECT * FROM ", @other_table);
mysql> PREPARE stmt FROM @s;
mysql> EXECUTE stmt;
mysql> DEALLOCATE stmt;

这里WHERE 1=1应该更改为只返回结果集中的一行

最新更新