简体   繁体   中英

Selecting 'field_name' from multiple tables in SQL?

It may seem quit basic but I've not come across this yet and can't figure it out. Say I have two tables of users and in each table is a field 'email_address'. How can I select all email addresses from both tables as one list? I'll most likely need the DISTINCT keyword since there may be occurrences of the same email address in both tables.

I bet it's deadly obvious and I just can't see the logic.

select email_address from table1
union
select email_address from table2

UNION will merge the identical email adresses.

If you wanna keep the duplicates, use UNION ALL

Just UNION the two tables:

SELECT `email_address`
FROM `a`
UNION
SELECT `email_address`
FROM `b`
select EMAIL_NAME from table1
UNION
select EMAIL_NAME from table2

Use a UNION:

SELECT email_address FROM table1
UNION
SELECT email_address FROM table2

Use a union, and if you want to know which came from which table, put a literal of the table name in your result set.

select email_name, 'table1' as table_name from table1
union
select email_name, 'table2' as table_name from table2

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.

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