我有两个选择陈述
1
select Start_Date
from table1 where Start_Date not in (
select End_Date
from table1)
2
select End_Date from table1
where End_Date not in (
select Start_Date
from table1
)
我希望在使用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
它给我结果每个记录重复四次帮助我下一步做什么??
答案 0 :(得分: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
如果您的查询返回的行数超过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)
)
您可以使用JOIN
如果你有一个字段用作“Join On”你可以使用这个字段,如果没有你可以添加一个字段来加入(但你需要检查返回的数据以避免错误)
你还要检查什么样的连接可能对你有好处(内 - 左 - rigth)
在示例中,我添加了一个要加入的字段并使用内部联接:
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)