如何从SELECT语句的子查询中获得非空结果?
SELECT a, b, c,
(SELECT d
FROM table2
WHERE ...) as d
FROM table 1
WHERE ...
我只想在所有值(a,b,c,d)不为Null时获得结果。 在主WHERE子句中也使用相同的子查询,但使用EXISTS并不是一种奇怪/低效率的方法吗?
答案 0 :(得分:3)
最简单的方法是将原始查询放在子查询中,然后可以检查子查询返回的整行是否为NULL:
SELECT *
FROM (
SELECT a, b, c,
(SELECT d
FROM table2
WHERE ...)
FROM table 1
WHERE ...
) AS sub
WHERE sub IS NOT NULL
sub
是子查询返回的(a,b,c,d)
行。
答案 1 :(得分:0)
SELECT
t1.a,
t1.b,
t1.c,
t2.d
FROM table1 t1
left join table2 as t2 on t2.ID = t1.ID
WHERE t1.a is not null and t1.b is not null and t1.c is not null and t2.d is not null
答案 2 :(得分:0)
您可以使用子查询:
select a, b, c, d
from (SELECT a, b, c,
(SELECT d
FROM table2
WHERE ...) as d
FROM table 1
WHERE ... and
a is not null and b is not null and c is not null
) x
where d is not null;
不过,您很可能可以使用JOIN
:
SELECT a, b, c, x.d
FROM table 1 JOIN
(SELECT d
FROM table2
WHERE ...
) x
WHERE ... and
a is not null and b is not null and c is not null and d is not null;