Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add "field" of table name to SQL results from UNION?

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 |
+--------+-------+---------+
like image 946
bearfriend Avatar asked Oct 20 '12 20:10

bearfriend


People also ask

Can you UNION tables with different column names?

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.

Can you UNION columns in SQL?

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.


1 Answers

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;
like image 142
Roman Pekar Avatar answered Nov 06 '22 15:11

Roman Pekar