MySQL - 总是返回n条记录

时间:2014-08-27 21:47:41

标签: mysql sql

对于任何给定的外键ID,我都有一个包含许多(总是至少1个,有时超过6个)值的表。这是一个查询,它使值下降并将输出限制为最多6个值:

SELECT Diameter
FROM  `TreeDiameters` 
WHERE TreeID = ?
ORDER BY Diameter DESC 
LIMIT 0 , 6;

但是我怎样才能总是得到6个值(额外的值为NULL或空白或其他)?

1 个答案:

答案 0 :(得分:2)

您可以使用union alllimit

执行此操作
(SELECT Diameter
 FROM  `TreeDiameters` 
 WHERE TreeID = ?
) union all
(select NULL as Diameter
 from (select 1 as n union all select 2 union all select 3 union all select 4 union all
       select 5 union all select 6
      ) n 
)
ORDER BY Diameter DESC
LIMIT 0, 6;

MySQL将NULL值放在最后一个降序排列。但你也可以具体:

ORDER BY (Diameter is not null) DESC, Diameter DESC