单个查询可以选择多个 - 如果一个选择返回空,则为

时间:2015-09-25 16:46:39

标签: mysql select ifnull

我需要制作几个select语句来获取简单数据(只有一行包含每个选择的一个或多个字段)。

简化示例:

select name, price from article where id=125
select log, email from user where uid=241

我想只处理来自php端的一个语句(或者:我不想准备几个语句,执行多个语句,捕获并处理每个执行的异常,最后获取每个语句的结果声明...)。
我试过了:

select * from (
  (select name, price from article where id=125) as a,
  (select log, email from user where uid=241) as b
)

如果每个subselect返回值,则效果很好:

name  |  price  | log  | email
------------------------------------------
dummy |  12,04  | john | john@example.com

如果其中一个子选择返回空,则整个选择返回空 我想要的是:空的结果子选择的空值 我使用ifnull()coalesce()尝试了许多内容,但无法获得期待的结果(我知道如何使用null值,但我没有找到方法来处理在空结果集的情况下与他们一起) 我终于找到了一个左连接的解决方案:

select * from (
  (select 1) as thisWillNeverReturnEmpty
  left join (select name, price from article where id=125) as a on 1
  left join (select log, email from user where uid=241) as b on 1
)

即使其中一个子查询返回空(或者两者都是,因此"选择1"),它也能正常工作。
我在SO上找到的另一种方法是在每个子查询中添加count(*)以确保其中有值。

但这一切看起来都很脏,我无法相信只有使用ifnull()这样的东西并不简单。 什么是正确的方法?

1 个答案:

答案 0 :(得分:0)

我最终找到的最佳方式是:

select * from (
  (select count(*) as nbArt, name, price from article where id=125) as a,
  (select count(*) as nbUser, log, email from user where uid=241) as b
)

这样,没有子查询返回空,这解决了问题(总是至少有一个"零"计数后跟空值)。

找不到文章时的示例结果:

nbArt  |  name  |  price  |  nbUser  |  log  |  email
----------------------------------------------------------------
  0    |  null  |   null  |    1     |  john | john@example.com