SELECT ir.objectid,ir.objecttype,ir.name,ir.email,ir.createdate,
CASE objecttype
WHEN 1 THEN (select friendlyurl
from locations
where id = ir.objectid)
END as objecturl
FROM inforequests ir
WHERE createdate > '1/1/2014'
order by CreateDate asc
此查询为我返回10行,但是对于列objecturl
,1行显示NULL,如果在[locations]表中找不到记录,则会发生这种情况。
如何更改我的查询以确保当objecturl
为空时,不返回该行,因此在我的情况下,我的查询将只返回9行。
答案 0 :(得分:1)
将其添加到WHERE
子句:
where createdate > '1/1/2014' and objecttype = 1
由于CASE
不处理任何其他值,因此objecttype <> 1
时会导致NULL。
或者,您可以嵌套SELECT
s:
select *
from ( SELECT ir.objectid,ir.objecttype,ir.name,ir.email,ir.createdate,
CASE objecttype
WHEN 1 THEN (select friendlyurl
from locations
where id = ir.objectid)
END as objecturl
FROM inforequests ir
WHERE createdate > '1/1/2014' ) as Temp
where objecturl is not NULL
order by CreateDate asc
请注意,这有些不同,因为它还会排除相关子查询返回NULL的行。