0

这是我的桌子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 做到这一点?

4

1 回答 1

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
于 2013-11-14T15:10:13.717 回答