MYSQL 查询在 LEFT JOIN 中使用变量作为表名

发布于 2024-09-17 22:51:01 字数 310 浏览 6 评论 0原文

SELECT var1,var2,var3,table_name 
FROM table1 LEFT JOIN table_name on var3=table_name.id

这意味着我想动态左连接表,具体取决于 table1 中的 table_name 值,因为 var3 是从那里获取的。

但上面的查询结果是

表table_name不存在

我的mysql限制错误?

SELECT var1,var2,var3,table_name 
FROM table1 LEFT JOIN table_name on var3=table_name.id

Meaning I want to dynamically left join table, depending on value of table_name from table1, since var3 is taken from there.

But the above query results in

table table_name does not exist

My mistake of mysql limitation?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

行至春深 2024-09-24 22:51:01

表名以及列名在 SQL 查询中不能是动态的。因此,您必须以编程方式应用逻辑,使用 2 个查询或使用存储过程,请参阅此处的示例: http://forums.mysql.com/read.php?98,126506,126598#msg-126598

Table names, as well as column names, can't be dynamic in an SQL query. So you have to apply your logic programmatically, using 2 queries, or with a stored procedure, see an example here: http://forums.mysql.com/read.php?98,126506,126598#msg-126598

我很坚强 2024-09-24 22:51:01

另一种方法是将所有表与联合查询联合起来:

SELECT *, 44 as table_origin FROM `Table_44`
UNION ALL
SELECT *, 58 as table_origin FROM `Table_58`;

您甚至可以将其准备为视图:

CREATE VIEW `AllTheTables` AS
SELECT *, 42 as table_origin FROM `Table_42`
UNION ALL
SELECT *, 44 as table_origin FROM `Table_44`
UNION ALL
SELECT *, 58 as table_origin FROM `Table_58`
UNION ALL
SELECT *, 69 as table_origin FROM `Table_69`;

从而安全地查询它:

SELECT * FROM AllTheTables WHERE table_origin IN (44,58) AND something = 'foobar';
-- or --
SELECT * FROM AllTheTables WHERE table_origin = 42 AND something = 'the question';

在你的具体情况下,它可能看起来像这样:

SELECT var1, var2, var3, table_name 
FROM table1 LEFT JOIN AllTheTables ON table1.var3=AllTheTables.table_origin

Another way is to unite all tables with a union query:

SELECT *, 44 as table_origin FROM `Table_44`
UNION ALL
SELECT *, 58 as table_origin FROM `Table_58`;

You could even prepare that as view:

CREATE VIEW `AllTheTables` AS
SELECT *, 42 as table_origin FROM `Table_42`
UNION ALL
SELECT *, 44 as table_origin FROM `Table_44`
UNION ALL
SELECT *, 58 as table_origin FROM `Table_58`
UNION ALL
SELECT *, 69 as table_origin FROM `Table_69`;

And thus query it safely:

SELECT * FROM AllTheTables WHERE table_origin IN (44,58) AND something = 'foobar';
-- or --
SELECT * FROM AllTheTables WHERE table_origin = 42 AND something = 'the question';

In your exact case it could look like this:

SELECT var1, var2, var3, table_name 
FROM table1 LEFT JOIN AllTheTables ON table1.var3=AllTheTables.table_origin
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文