MySQL 重命名 SQL SELECT 语句中的列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12053327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 14:33:14  来源:igfitidea点击:

Renaming Columns in an SQL SELECT Statement

mysqlsql

提问by Andrew Cheong

I would like to rename the columns in the results of a SELECTexpression. Of course, the following doesn't work:

我想重命名SELECT表达式结果中的列。当然,以下方法不起作用:

SELECT * AS foobar_* FROM `foobar`

As I'm new to SQL, I think I'm just missing a concept, tool, or keyword that would lead to the answer. A hint in the right direction would be appreciated. Thanks!

由于我是 SQL 的新手,我认为我只是缺少一个可以找到答案的概念、工具或关键字。正确方向的提示将不胜感激。谢谢!

UPDATE

更新

I'm looking for a generic way to do this, and MySQL-specific techniques are absolutely fine.

我正在寻找一种通用的方法来做到这一点,而特定于 MySQL 的技术绝对没问题。

In short, I'm writing a tool that "exports" the results of MySQL queries to Google Spreadsheets (via the Google Data API). Some queries are joins, so to make columns unique I wanted to prefix all column names with their respective table names.

简而言之,我正在编写一个工具,将 MySQL 查询的结果“导出”到 Google 电子表格(通过 Google 数据 API)。有些查询是连接,所以为了使列唯一,我想用它们各自的表名作为所有列名的前缀。

回答by StuartLC

You can alias the column names one by one, like so

您可以一一为列名设置别名,就像这样

SELECT col1 as `MyNameForCol1`, col2 as `MyNameForCol2` 
FROM `foobar`

EditYou can access INFORMATION_SCHEMA.COLUMNSdirectly to mangle a new alias like so. However, how you fit this into a query is beyond my MySql skills :(

编辑您可以INFORMATION_SCHEMA.COLUMNS像这样直接访问以修改新别名。但是,如何将其放入查询中超出了我的 MySql 技能:(

select CONCAT('Foobar_', COLUMN_NAME)
from INFORMATION_SCHEMA.COLUMNS 
where TABLE_NAME = 'Foobar'

回答by Joe G Joseph

you have to rename each column

你必须重命名每一列

SELECT col1 as MyCol1,
       col2 as MyCol2,
 .......
 FROM `foobar`

回答by Shikha Singh

select column1 as xyz,
      column2 as pqr,
.....

from TableName;