I have several SELECT
queries in a UNION
statement (or UNION ALL
). 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.
I aliased the columns in each query, so I can use the data by name instead of index in my PHP script.
Is it possible to get the individual column names aliased from each individual 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,
$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.
You can't. A UNION is going to use the aliased column name from the first query (I think, it might be the last). That's the point of a 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:
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.