If I have a simple union
select name, phone from users union select name, phone from vendors;
Is there a way to add the table name to the results?
So instead of
+--------+-------+
| name | phone |
+--------+-------+
| Jim | 123...|
| Macy's | 345...|
+--------+-------+
I'd get
+--------+-------+---------+
| name | phone | table |
+--------+-------+---------+
| Jim | 123...| users |
| Macy's | 345...| vendors |
+--------+-------+---------+
Rules for using UNION You can put UNION between two SELECT statements only if the two statements select the same number of columns and the corresponding columns are compatible data types (for example, numeric to numeric). Corresponding columns in select statements merged by UNION do not need to have the same name.
Using UNION on Multiple FieldsWe can apply UNION on multiple columns and can also order the results using the ORDER BY operator in the end. This will result in the following: The result is sorted according to the “Dept_ID.” We can also filter the rows being retrieved by each SELECT statement.
select name, phone, 'users' as table_name from users
union
select name, phone, 'vendors' as table_name from vendors;
Better solution will be to use union all
, so server will not be checking for distinct values
select name, phone, 'users' as table_name from users
union all
select name, phone, 'vendors' as table_name from vendors;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With