选择一些项目,如果没有足够的项目,添加一些其他项目,然后排序

时间:2013-11-14 15:07:11

标签: mysql

这是我的表items

id    type        important    date                
--------------------------------------------------
1     articles    0            2013-11-14 01:10:00
2     articles    0            2013-11-14 02:45:00
3     articles    1            2013-11-15 03:00:00
4     articles    0            2013-11-15 04:23:00
5     articles    1            2013-11-17 05:21:00
6     news        0            2013-11-18 06:00:00
7     news        0            2013-11-19 07:00:00
8     news        0            2013-11-19 08:00:00

我需要显示三个重要的项目,或者,如果它们不够,则添加新闻到混合,直到有三个。然后按照从最新到最旧的日期对它们进行排序。

如果我这样写只是:

SELECT * FROM `items` WHERE important = 1 OR type = 'news' 
ORDER BY `important` DESC, `date` DESC LIMIT 3

然后两个重要项目将高于最新的新闻项目。但我需要得到这个:

id    type        important    date                
--------------------------------------------------
8     news        0            2013-11-19 08:00:00
5     articles    1            2013-11-17 05:21:00
3     articles    1            2013-11-15 03:00:00

如何使用SQL执行此操作?

1 个答案:

答案 0 :(得分:1)

这可以解决这个问题吗?

SELECT * FROM (
    SELECT * FROM `items` WHERE important = 1 OR type = 'news' 
    ORDER BY `important` DESC, `date` DESC LIMIT 3
) x
ORDER BY `date` DESC