简体   繁体   English

SQL Server:使用左联接从两个表中选择一列作为单列

[英]SQL Server: use left join to select a column from two tables as a single column

I am trying to build a select query that will essentially left join two tables and display one column from each table as a single column. 我正在尝试建立一个选择查询,该查询本质上将使两个表保持联接,并将每个表中的一列显示为单列。

the table structure is similar to: 表结构类似于:

table a: 表一:

id, email

table b: 表b:

id, tablea_id, email

I am trying to get a single column of email and email (with no dupes or nulls ideally). 我正在尝试获取电子邮件和电子邮件的单个列(理想情况下没有重复或空值)。

ideal results would be: 理想的结果是:

one@one.com
two@two.com
three@three.com

and the email address that is returned could be from either a or b. 并且返回的电子邮件地址可能来自a或b。

Maybe a union is what would work best, but I not able to figure out how to do a union on the second table based on the id of the first table. 也许联合会是最有效的,但是我无法根据第一个表的ID找出如何在第二个表上进行联合。

When searching for a solution, perhaps my wording is bad, but I can't find any examples. 在寻找解决方案时,也许我的措辞不好,但是我找不到任何示例。

thanks for any help. 谢谢你的帮助。

It seems that you want something on the lines of this: 似乎您需要以下内容:

SELECT email
FROM TableA
UNION
SELECT B.email
FROM TableA A
JOIN TableB B
ON A.id = B.TableA_id

If you simply want a unique list of email addresses from either table you can do: 如果您只想从任一表中获得唯一的电子邮件地址列表,则可以执行以下操作:

Select email
From TableA
Union
Select email
From TableB

If you are looking for a unique list of email addresses from Table B and those from Table A that exist in Table B, then you can do: 如果要查找表B和表B中存在的表A的电子邮件地址的唯一列表,则可以执行以下操作:

Select TableA.email
From TableA
    Join TableB
        On TableB.TableA_id = TableA.id
Union
Select email
From TableB

If, per your comments, you need all rows from Table A and only rows from Table B where they exist in Table A: 如果根据您的评论,您只需要表A中的所有行,而仅表B中存在的表B中的行:

Select email
From Table A
Union 
Select TableB.email
From TableB
    Join TableA
        On TableA.id = TableB.TableA_id

这个怎么样:

SELECT DISTINCT a.email+ ' ' + b.email FROM tableA a LEFT JOIN tableB b on a.Id = b.tablea_Id WHERE b.email IS NOT NULL

This could help: 这可以帮助:

SELECT
    id, email
FROM
    a

UNION

(
    SELECT
        a.id AS id, b.email AS email
    FROM
        b
    INNER JOIN
        a
    ON
        a.id = b.tablea_id
) b

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

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