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

标签 mysql

我有两个选择语句

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/

相关文章:

php - 将整个 HTML 代码插入到内容表中

javascript - 如何复制这个 JS 变量并更改使用的文本?

mysql - 提高 MySQL 查询性能 - 数学密集型查询

mysql - 为什么在执行子查询时出现 MySQL 语法错误?

mysql - 如何使用虚拟实体数据预填充数据库?

php - 通过 jquery 使用 mysql 中的数据更改 opener 文档的值

php - CodeIgniter SQL 查询不返回逻辑结果

mysql - magento 的服务器解决方案

Mysql,无法创建表

mysql - 如何在查询中使用变量