简体   繁体   English

SQL Server是否可以使用PHP从UNION查询返回不同的别名列名?

[英]Is it possible for SQL Server to return different aliased column names from a UNION query using PHP?

I have several SELECT queries in a UNION statement (or UNION ALL ). 我在UNION语句(或UNION ALL )中有几个SELECT查询。 As it is a UNION it is going to return the single dataset with one column (I only have one value return in this case), typically the column name from the first query. 由于它是UNION它将返回具有一列的单个数据集(在这种情况下我只有一个值返回),通常是第一个查询中的列名。

I aliased the columns in each query, so I can use the data by name instead of index in my PHP script. 我在每个查询中别名列,因此我可以在PHP脚本中按名称而不是索引使用数据。

Is it possible to get the individual column names aliased from each individual SELECT ? 是否可以从每个SELECT获取别名的各个列名?

Consider, 考虑,

SELECT name as manager FROM employees WHERE type = 1
UNION
SELECT name as mid_level_manager FROM employees WHERE type = 2
UNION
SELECT name as regular_employee FROM employees WHERE type = 3

I am using PDO with Prepared Statements, like this, 我正在使用PDO和Prepared Statements,像这样,

$results = $prepared_statement->fetchAll(PDO::FETCH_ASSOC);

Maybe not the best example, but how could I get those aliased column names? 也许不是最好的例子,但我怎么能得到那些别名的列名? Query works fine in and of itself. 查询工作正常。 I am using SQL Server 2012. 我正在使用SQL Server 2012。

You can't. 你不能。 A UNION is going to use the aliased column name from the first query (I think, it might be the last). UNION将使用第一个查询中的别名列名(我想,它可能是最后一个)。 That's the point of a UNION. 这就是UNION的观点。

You can select multiple columns and alias each one, but you can't have a different column alias for different rows , that does not make sense. 您可以为每个列选择多个列和别名,但不能为不同的设置不同的列别名,这没有意义。

There's only a single name for a single column, but you might add the type column indicating which select returned that row: 单个列只有一个名称,但您可以添加type列,指示返回该行的选择:

SELECT type, name as manager FROM employees WHERE type = 1
UNION
SELECT type, name as mid_level_manager FROM employees WHERE type = 2
UNION
SELECT type, name as regular_employee FROM employees WHERE type = 3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM