在两列中合并两个select语句?

Muh*_*mar 3 mysql

我有两个选择声明

1

select Start_Date
    from table1  where Start_Date not in (
    select End_Date
    from table1)
Run Code Online (Sandbox Code Playgroud)

2

 select End_Date from table1
    where End_Date not in (
        select Start_Date
            from table1
        )
Run Code Online (Sandbox Code Playgroud)

我想在我使用union时将不同列中的两个select语句组合在一起它给我一个列,其中两个查询的结果我希望每个查询结果在不同的列中,但是当我使用内部联接时

select a.End_Date , b.Start_Date from
( select End_Date from table1
where End_Date not in (
select Start_Date
from table1
) ) a

join

(select Start_Date
from table1 where Start_Date not in (
select End_Date
from table1)
) b
on 1=1
Run Code Online (Sandbox Code Playgroud)

它给我的结果每个记录重复四次帮助我下一步做什么?

gen*_*pos 5

如果您的每个查询只返回1行,您可以使用:

SELECT 
(select Start_Date
    from table1  where Start_Date not in (
        select End_Date
        from table1)
) AS StartDate,
 (select End_Date from table1
    where End_Date not in (
        select Start_Date
        from table1)
 ) AS EndDate
Run Code Online (Sandbox Code Playgroud)

如果您的查询返回超过1行,则必须选择其他解决方案:

您可以使用UNION:(您将在另一列中将两个查询与"NULL"未对齐)

(select Start_Date, Null AS EndDate
    from table1  where Start_Date not in (
         select End_Date
         from table1)
) 
UNION
(select  Null As StartDate, End_Date 
    from table1
    where End_Date not in (
        select Start_Date
        from table1)
 ) 
Run Code Online (Sandbox Code Playgroud)

你可以使用JOIN 如果你有一个字段用作"加入"你可以使用这个字段,如果没有你可以添加一个字段加入(但你需要检查返回的数据以避免错误)另外你必须检查什么样的join可能对你有用(Inner - Left - rigth)在这个例子中,我添加一个字段来加入并使用Inner Join:

SELECT Start_Date, End_Date
FROM
(select 1 as InnerId, Start_Date
    from table1  where Start_Date not in (
        select End_Date
        from table1)
) As Tab1
 INNER JOIN
 (select  1 as InnerId, End_Date from table1
    where End_Date not in (
        select Start_Date
        from table1)
 ) AS Tab2
USING(InnerId)
Run Code Online (Sandbox Code Playgroud)