MYSQL:带来带有表别名的列名的联接结果
我运行
select * from tableA as AA join tableB as BB;
There are many same columns in the table,因此我希望所有列在输出时都以表别名为前缀。例如:AA.id,...,BB.id,...
我该怎么做?
编辑:我知道我可以手动命名列,但我希望所有列都以表别名自动命名。
谢谢
I run
select * from tableA as AA join tableB as BB;
There are many identical columns in the tables so I want all the columns be prefixed on output by the table alias. Like: AA.id, ..., BB.id, ...
How can I do this?
edit: I know that I can name columns manually, but I'd like all of them be named automatically after the table aliases.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
select *
是“懒惰”的。您应该始终指定所需的字段,如果两个表之间存在冲突,则必须明确指定所需的冲突字段以及来自哪个表。是的,这很乏味,特别是如果你确实想要所有字段,但这就是生活......
select *
is "lazy". You should always specify which fields you want, and if there's conflicts between the two tables, you do have to explicitly specify which of the conflicting fields you want, and from which table.Yes, it's tedious, especially if you DO want all the fields, but that's life...
还创建列名别名。当然,您必须在输出中提及您想要的每个列名称,而不是
*
,没有自动版本。create column name alias as well. Of course, You have to mention every column name which you want in output instead of
*
there is no automate version of this.您可以使用:
忽略这将在 MySQL 上产生的笛卡尔积,它不会缓解您仍然难以从任一表中的同名列检索值的事实。
SELECT *
也是不好的做法,可能会导致检索不需要的数据。您必须为同名列定义列别名,或者更改表以更改列名称。
You can use:
Ignoring the cartesian product this will produce on MySQL, it won't alleviate the fact that you will still have difficulty retrieving values from identically named columns in either table.
SELECT *
is also bad practice, risking data retrieval that you don't need.You will have to define column aliases for identically named columns, or alter the tables to change the column names.
动态命名列的最简单方法是生成引用 information_schema 的预准备语句。这将为您提供您正在寻找的结果。
没有 AA、BB 别名,更简单。上述方法要求您在每个表的表注释字段中设置这些字段,可在 INFORMATION_SCHEMA.TABLES.TABLE_COMMENT 中找到。更新 information_schema.tables set table_comment = 'AA' 等...
GROUP_CONCAT() 函数的默认限制为 1024 个字符,因此根据表中的列数,您可能需要提高此限制才能生成准备好的声明。
如果需要,此命令将提高组连接限制。
The easiest way to dynamically name columns is to generate a prepared statement that references the information_schema. This would give you the results you were looking for.
It's simpler without the AA, BB aliases. The method above requires that you set these in the table comment field for each table, found in INFORMATION_SCHEMA.TABLES.TABLE_COMMENT. Update information_schema.tables set table_comment = 'AA' etc...
The GROUP_CONCAT() function has a default limit of 1024 characters, so depending on the number of columns in your tables, you may need to raise this limit in order to generate the prepared statement.
This command will raise the group concat limit if needed.