0

我正在使用 union all 来联合多个查询,但 union all 并没有为这些零值插入一个空行。我查看了该站点,根据这个问题,它应该包括它们:

具有 NULL 字段的 mysql 联合

这些是我的疑问:

select [SMTH] from [H].[D].[T]
where Date = (SELECT MAX(DATE) from [H].[D].[T] where Data = 1 and SMTH > 0 )  
union all
select [SMTH] from [H].[D].[T]
where Date = (SELECT MAX(DATE) from [H].[D].[T] where Data = 2 and SMTH > 0 )  
union all
select [SMTH] from [H].[D].[T]
where Date = (SELECT MAX(DATE) from [H].[D].[T] where Data = 3 and SMTH > 0 )  
union all
select [SMTH] from [H].[D].[T]
where Date = (SELECT MAX(DATE) from [H].[D].[T] where Data = 4 and SMTH > 0 )  

结果:

10068
3967
895

四个独立查询:

select [SMTH] from [H].[D].[T]
where Date = (SELECT MAX(DATE) from [H].[D].[T] where Data = 1 and SMTH > 0 )  

select [SMTH] from [H].[D].[T]
where Date = (SELECT MAX(DATE) from [H].[D].[T] where Data = 2 and SMTH > 0 )  

select [SMTH] from [H].[D].[T]
where Date = (SELECT MAX(DATE) from [H].[D].[T] where Data = 3 and SMTH > 0 )  

select [SMTH] from [H].[D].[T]
where Date = (SELECT MAX(DATE) from [H].[D].[T] where Data = 4 and SMTH > 0 )   

结果:

10068
3967
0
895

所以基本上因为我认为上一个问题的答案是正确的,我做错了什么?

谢谢!

4

2 回答 2

2

哪一列是空的?您确定,由于您的 where 子句,没有删除空值吗?请记住,使用 null 的操作总是会导致 null(使用 IS NULL 进行测试除外)。

于 2012-09-20T09:49:03.287 回答
0

第三个查询返回 0。为什么你认为它是 null?无论如何,这个查询都比union

如果表有主键(此查询中的 id):

select SMTH, Data, [date]
from 
    H.D.T
    inner join (
        select id, Data, max([date]) as [date]
        from H.D.T
        where Data in (1, 2, 3, 4) and SMTH > 0
        group by id, Data
    ) s on s.id = H.D.T.id
order by Data
于 2012-09-20T11:12:08.207 回答