我有一个查询,如果在IN子句中找到值,则返回记录。匹配的记录从0到1不等,因此查询结果也是如此。但我希望将计数设为5,即使其余行填充NULL也是如此。有什么办法可以实现吗? 至于给定的查询
SELECT categoryID, categoryName
FROM category
WHERE categoryID
IN ( 52, 58, 60 , 62 , 64)
我只有前3个ID的值,因此结果只给我3行。但我希望结果的计数为5,其余的非满足行填充空值以进行计数。 目前的结果:
CategoryID CategoryName
52 ABC
58 XYZ
60 DEF
所需的结果
CategoryID CategoryName
52 ABC
58 XYZ
60 DEF
NULL NULL
NULL NULL
答案 0 :(得分:3)
将LEFT JOIN
与合成表一起使用,列出所需的所有类别ID:
SELECT c.categoryID, c.categoryName
FROM (SELECT 52 AS categoryID
UNION SELECT 58 UNION SELECT 60 UNION SELECT 62 UNION SELECT 64) AS a
LEFT JOIN category AS c ON a.categoryID = c.categoryID
另一种方法是创建一个包含所有可能类别ID的表。然后使用:
SELECT c.categoryID, c.categoryName
FROM allCategories AS a
LEFT JOIN category AS c ON a.categoryID = c.categoryID
WHERE a.categoryID IN (52, 58, 60 , 62 , 64)
答案 1 :(得分:1)
在末尾添加5个空行,只选择前5行。
SELECT categoryID, categoryName FROM (
SELECT categoryID, categoryName, 1 as ord
FROM category
WHERE categoryID
IN ( 52, 58, 60 , 62 , 64)
UNION ALL
SELECT NULL as categoryID, NULL as categoryName, 0 as ord
UNION ALL
SELECT NULL as categoryID, NULL as categoryName, 0 as ord
UNION ALL
SELECT NULL as categoryID, NULL as categoryName, 0 as ord
UNION ALL
SELECT NULL as categoryID, NULL as categoryName, 0 as ord
UNION ALL
SELECT NULL as categoryID, NULL as categoryName, 0 as ord )t
ORDER BY ord desc LIMIT 0,5;