在 MySQL 中选择表名作为 UNION select 查询中的列

发布于 2024-10-04 22:13:20 字数 183 浏览 2 评论 0原文

我希望能够选择行所在的表的名称作为联合选择查询中的列。像这样的事情:

SELECT [TABLENAME], text from table1
UNION
SELECT [TABLENAME], text from table2
ORDER BY date

有谁知道这是否可能? 谢谢

I want to be able to select the name of a the table a row is from as a column in a union select query. Something like this:

SELECT [TABLENAME], text from table1
UNION
SELECT [TABLENAME], text from table2
ORDER BY date

Does anyone know if this is possible?
Thanks

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

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

发布评论

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

评论(2

衣神在巴黎 2024-10-11 22:13:21

您已经在查询该表本身。例如:- table1 和 table2

所以你基本上可以将表名称输出为字符串本身 -

SELECT 'table1' as tableName, text from table1
UNION
SELECT 'table2' as tableName, text from table2
ORDER BY date

You are already querying on that table itself. Eg:- table1 and table2

So you can basically output table name as string itself -

SELECT 'table1' as tableName, text from table1
UNION
SELECT 'table2' as tableName, text from table2
ORDER BY date
等待我真够勒 2024-10-11 22:13:21

既然你必须在 sql 中输入表名,为什么不把它作为字符串包含在 select 中呢? IE

SELECT 'table1' as tablename, text from table1
UNION
SELECT 'table2' as tablename, text from table2
ORDER BY date

given that you've got to type the table name into the sql anyway, why not just include it as a string in the select too? i.e.

SELECT 'table1' as tablename, text from table1
UNION
SELECT 'table2' as tablename, text from table2
ORDER BY date
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文