在 MySQL SELECT "AS" 中使用表名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12132558/
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
Use table name in MySQL SELECT "AS"
提问by preyz
I use the table name to build a nested array when I evaluate my MySQL SELECT JOIN result in PHP. However, when working with AS for calculated columns, I can't seem to set the table name as intended (to simplify, I am trying without a JOIN in this example, but the problem is the same):
当我在 PHP 中评估我的 MySQL SELECT JOIN 结果时,我使用表名来构建嵌套数组。但是,当使用 AS 处理计算列时,我似乎无法按预期设置表名(为简化起见,我在此示例中尝试不使用 JOIN,但问题是相同的):
SELECT `field1`, `field2`, "Test" AS `Table`.`field3` FROM `Test`;
This throws an error.
这会引发错误。
How can I indicate in the SQL, which table I want to associate field3 with?
如何在 SQL 中指明我想将 field3 与哪个表关联?
(resulting in the table name in $pdoStatement->getColumnMeta()
being "Table")
(导致表名$pdoStatement->getColumnMeta()
是“表”)
回答by Michael Berkowski
To declare a string literal as an output column, leave the Table
off and just use Test
. It doesn't need to be associated with a table among your joins, since it will be accessed only by its column alias. When using a metadata function like getColumnMeta()
, the table name will be an empty string because it isn'tassociated with a table.
要将字符串文字声明为输出列,请Table
关闭并使用Test
. 它不需要与联接中的表相关联,因为它只能通过其列别名进行访问。当使用元数据函数时getColumnMeta()
,表名将是一个空字符串,因为它不与表相关联。
SELECT
`field1`,
`field2`,
'Test' AS `field3`
FROM `Test`;
Note: I'm using single quotes above. MySQL is usually configured to honor double quotes for strings, but single quotes are more widely portable among RDBMS.
注意:我在上面使用单引号。MySQL 通常配置为支持字符串的双引号,但单引号在 RDBMS 中更广泛地可移植。
If you musthave a table alias name with the literal value, you need to wrap it in a subquery with the same name as the table you want to use:
如果你必须有一个带有字面值的表别名,你需要将它包装在一个与你要使用的表同名的子查询中:
SELECT
field1,
field2,
field3
FROM
/* subquery wraps all fields to put the literal inside a table */
(SELECT field1, field2, 'Test' AS field3 FROM Test) AS Test
Now field3
will come in the output as Test.field3
.
现在field3
将作为Test.field3
.
回答by Aghilas Yakoub
SELECT field1
, field2
, 'Test' AS field3
FROM Test
; // replace with simple quote '
SELECT field1
, field2
, 'Test' AS field3
FROM Test
; // 替换为简单的引号 '