我有两个选择语句
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 all 时,我想在不同的列中组合两个 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
它给我的结果是每条记录都重复四次,这有助于我下一步做什么??
最佳答案
如果您的每个查询仅返回 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
如果你有一个字段用作“加入”你可以使用这个字段,如果没有你可以添加一个字段来加入(但你需要检查返回的数据以避免错误)
您还必须检查哪种连接可能对您有好处(内 - 左 - 右)
在示例中,我添加了一个要加入的字段并使用了内部联接:
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)
关于mysql - 在两列中合并两个 select 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33790771/