简体   繁体   English

在SQL中从多个表中选择“ field_name”?

[英]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'. 假设我有两个用户表,每个表中都有一个字段“ 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. 我很可能需要DISTINCT关键字,因为两个表中都可能出现相同的电子邮件地址。

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. UNION将合并相同的电子邮件地址。

If you wanna keep the duplicates, use UNION ALL 如果您想保留重复项,请使用UNION ALL

Just UNION the two tables: 只是UNION这两个表:

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: 使用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

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

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