当一个子查询找不到结果时,UNION ALL返回错误?

时间:2011-12-21 23:44:15

标签: mysql

这是我的疑问:

SELECT UID, COUNT( * ) *100 AS Points
FROM  `Visited` 
WHERE UID =  '25'
UNION ALL 
SELECT UID, COUNT( * ) *1000 AS Points
FROM  `Sites` 
WHERE UID =  '25'
UNION ALL 
SELECT UID, COUNT( * ) *1000 AS Points
FROM  `userTags` 
WHERE UID =  '25'

当我运行它时,其中一个子查询没有找到任何结果:

#1048 - Column 'UID' cannot be null

我真的不明白这个问题,运行只提供没有结果的子查询可以正常工作并显示:

UID  | POINTS
NULL    0 

然而,由于某种原因,大查询不会将其统一起来。可能是什么原因?

----编辑

此外,如果三个子查询给出结果,查询工作正常。唯一的问题是其中一个没有结果。

1 个答案:

答案 0 :(得分:0)

UID = 25似乎没有匹配的行,但是COUNT(*)仍会返回一行,说明有0个匹配的行。您可以使用UID不为空的外部选择删除行,或者更简单地替换NULL,如下所示:

SELECT UID, COUNT( * ) *100 AS Points
FROM  `Visited` 
WHERE UID =  '25'
UNION ALL 
SELECT ifnull(UID, '25'), COUNT( * ) *1000 AS Points
FROM  `Sites` 
WHERE UID =  '25'
UNION ALL 
SELECT UID, COUNT( * ) *1000 AS Points
FROM  `userTags` 
WHERE UID =  '25';

当然,您可以将'25'替换为$uid,以便从代码中运行。

如果您认为可能没有匹配的行

,也会对其他表执行相同的操作