SQL 如何在选择时重命名表中的单个列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/614238/
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
How can I rename a single column in a table at select?
提问by akosch
I have two tables with one identical column name, but different data. I want to join the tables, but access both columns (row["price"], row["other_price"]): How can I rename/alias one of them in the select statement? (I do not want to rename them in the DB)
我有两个表,列名相同,但数据不同。我想加入表,但访问两列(行[“价格”],行[“other_price”]):如何在选择语句中重命名/别名其中之一?(我不想在数据库中重命名它们)
回答by MrTelly
select table1.price, table2.price as other_price .....
选择 table1.price, table2.price 作为 other_price .....
回答by Matt
select t1.Column as Price, t2.Column as Other_Price
from table1 as t1 INNER JOIN table2 as t2
ON t1.Key = t2.Key
like this ?
像这样 ?
回答by Dead account
us the AS keyword
我们的 AS 关键字
select a.Price as PriceOne, b.price as PriceTwo
from tablea a, tableb b
回答by Lucio Mollinedo
If, like me, you are doing this for a column which then goes through COALESCE / array_to_json / ARRAY_AGG / row_to_json (PostgreSQL) and want to keep the capitals in the column name, double quote the column name, like so:
如果像我一样,您正在为一个列执行此操作,该列然后通过 COALESCE / array_to_json / ARRAY_AGG / row_to_json (PostgreSQL) 并希望将大写字母保留在列名中,请将列名双引号,如下所示:
SELECT a.price AS "myFirstPrice", b.price AS "mySecondPrice"
Without the quotes (and when using those functions), my column names in camelCase would lose the capital letters.
如果没有引号(以及使用这些函数时),我在驼峰式大小写中的列名将丢失大写字母。
回答by Kunal S
if you are using sql server, use brackets or single quotes around alias name in a query you have in code.
如果您使用的是 sql server,请在代码中的查询中使用括号或单引号将别名括起来。
回答by Kunal S
Also you may omit the AS keyword. SELECT row1 Price, row2 'Other Price' FROM exampleDB.table1;
in this option readability is a bit degraded but you have desired result.
您也可以省略 AS 关键字。SELECT row1 Price, row2 'Other Price' FROM exampleDB.table1;
在此选项中,可读性有点下降,但您已获得所需的结果。
回答by Moayad Hani Abu Rmilah
There is no need to use AS
, just use:
无需使用AS
,只需使用:
SELECT table1.price Table1 Price, table2.price Table2 Price, .....
回答by u7786739
Another option you can choose:
您可以选择的另一个选项:
select price = table1.price , other_price = table2.price from .....
Reference:
参考:
In case you are curious about the performance or otherwise of aliasing a column using “=” versus “as”.
如果您对使用“=”与“as”对列进行别名的性能或其他方面感到好奇。