【问题标题】:How to get result of sub-query even if main query doesn't return any row?即使主查询不返回任何行,如何获得子查询的结果?
【发布时间】:2017-09-12 11:05:24
【问题描述】:

这是我的第一个查询

select column1, column2, column3 from table1 where id=2 LIMIT 1

这是我的第二个查询

select COUNT(*) from table2 where id=22

这是我的第三个查询

select COUNT(*) from table2 where column1='bla bla bla' AND id=33

我想将第一个查询中的第二个和第三个查询合并为这样的子查询

select column1, column2, column3 (select COUNT(*) from table2 where id=22) as count1, (select COUNT(*) from table2 where column1='bla bla bla' AND id=33) as count2 from table1 where id=2 LIMIT 1

如果主查询根据您的 where 条件给出结果,这可以正常工作。如果主查询没有返回任何行,那么我也无法知道 count1count2。但我想知道第二个和第三个子查询的结果(即 count1count2),即使主查询没有返回任何行。

我该怎么做?

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    将子查询移至from 子句并使用left join

    select column1, column2, column3, t22.cnt, t33.cnt_blablabla
    from (select cnt(*) as cnt from table2 where id = 22) t22 cross join
         (select count(*) as cnt_blablabla from table2 where column1 = 'bla bla bla' and id = 33) t33 left join
         table1 t1
         on t1.id = 2
    limit 1
    

    【讨论】:

    • 它工作正常......完美解决了我的问题......感谢您的回答
    猜你喜欢
    • 2019-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多