我需要创建几个选择语句来获取简单的数据(每个选择只有一行包含一个或多个字段)。
简化示例:
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
)
如果每个子选择都返回值,则效果很好:
name | price | log | email
------------------------------------------
dummy | 12,04 | john | john@example.com
但如果其中一个子选择返回空,则整个选择返回空。
我想要的是:空结果子选择的空值。我用and
尝试了很多东西,但无法得到期待的结果(我知道如何将它们与空值一起使用,但在结果集为空的情况下我没有找到处理它们的方法)。
我终于找到了左连接的解决方案: ifnull()
coalesce()
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()
. 正确的方法是什么?