【问题标题】:combine two select statement in two column?在两列中合并两个选择语句?
【发布时间】:2020-04-02 02:56:43
【问题描述】:

我有两个select语句

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

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

【问题讨论】:

  • 结果的每一行的两个日期应该如何配对?
  • 您能否展示一些示例输入和所需的结果?

标签: mysql


【解决方案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)

【讨论】:

  • 这不是和其他两个答案一样,只是不太详细吗?
  • @Barmar 这不是加入。只需为每个 Select 提供一列。您可以在每个选择的“)”之后使用“as columnName”为列命名
  • 如果(select) 子查询返回多于1 行,则不能将其放入SELECT 子句中。
  • 我不明白你的评论。其他答案没有连接。此后它们已被删除,因为它们不起作用。
  • @Barmar 我正在用手机写信,无法复制/粘贴。我将尝试编辑我的答案以更清楚
猜你喜欢
  • 1970-01-01
  • 2018-05-10
  • 1970-01-01
  • 2011-08-27
  • 2010-11-24
  • 1970-01-01
  • 2017-04-09
  • 1970-01-01
相关资源
最近更新 更多