我在从子查询中进行选择时遇到问题。如果所有子查询都返回一个值,则一切正常,并且返回包含我需要的所有值的行。
但是,如果一个子查询为 null 或为空,即使其他六个子查询返回一个值,我也会返回一个空集。
这是为什么呢?我怎样才能绕过它?我尝试使用“isnull”和其他技巧,但没有成功。我不明白设计以及为什么如果只有一个子查询失败,结果将作为空集返回。有哪些可能的解决方法?
我尝试使用“UNION”,但这有其自身的挑战,因为理想情况下我需要返回一行,以便 Perl/DBI 可以将结果放入哈希中,并且我可以匹配返回到列名称的值等。
SELECT * FROM (
(select p.pesticides from pesticides p WHERE p.id=? and p.companyid=?) AS pesticides,
(select d.directions from directions d WHERE d.id=?) AS directions,
( select i.intended from intended i where i.id=?) AS intended,
(select c.chemicals from chemicals c where c.id=? and c.companyid=?) AS chemicals,
(select a.aids from aids a where a.id=? and a.companyid=?) AS aids,
(select ing.ingredients from ingredients ing where ing.id=? and ing.companyid=?) AS ingredients,
(select s.solvents from solvents s WHERE s.id=? and s.companyid=?) AS solvents,
(select aller.allergens from allergens aller where aller.id=?) AS allergens)
最佳答案
当任何一个子查询不返回任何行时,它会返回一个空行集,因为子查询集被视为中间表。具体来说,以 SELECT * FROM (
启动 SQL告诉编译器括号内的部分是中间表。
您可以将每个子查询视为一列(子选择),如下所示:
create table T1(ID int, STR varchar(255));
create table T2(ID int, STR varchar(255));
insert into T1(ID, STR) values (1, 'One'), (2, 'Two'), (3, 'Three');
insert into T2(ID, STR) values (4, 'Four'), (5, 'Five'), (6, 'Six');
select
(select STR from T1 where ID = 1) COL1
,(select STR from T2 where ID = 4) COL2
;
当所有子查询返回单行时,这将与您的方法相同:
不同之处在于当一个或多个子选择不返回一行时会发生什么。该列简单地变为 NULL:
select
(select STR from T1 where ID = 1) COL1
,(select STR from T2 where ID = 8) COL2 -- ID 8 does not exist
;
针对 MySQL 的 SQL 操作:http://sqlfiddle.com/#!9/f1a209/1
关于如果子查询之一为空,Mysql select from subqueries返回空集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73116418/