我有下表名为Agenda:
ID:visible:sticky:startdate
1: 1: 1:2014-03-08
2: 1: 0:2014-02-25
3: 1: 0:2014-02-27
4: 1: 0:2014-02-20
5: 1: 0:2014-03-12
(ID->int, visible->tinyint, sticky->tinyint, startdate->date)
我正在运行以下查询以按日期获取下三个议程项目,当然正常工作。返回ID为4,2,3
SELECT *
FROM agenda
WHERE visible
AND startdate >= "2014-02-12"
ORDER BY startdate ASC
LIMIT 3
但我想要的是优先考虑粘性= 1的字段,如果有字段设置它们,它们应该在结果中并在ORDER BY中计算。所以我希望它返回的是ID的4,2,1
如何实现这一目标?
答案 0 :(得分:2)
SELECT *
FROM (
SELECT * FROM
agenda
WHERE visible
AND startdate >= "2014-02-12"
ORDER BY sticky DESC, startdate ASC
LIMIT 3
) subquery
ORDER BY startdate ASC
答案 1 :(得分:0)
这会将粘性设置在结果的顶部,据我所知,没有办法在中途包含它们,你总是可以使用2个查询并将结果组合在一个数组中,然后按日期排序。
SELECT *
FROM agenda
WHERE visible
AND startdate >= "2014-02-12"
ORDER BY sticky DESC , startdate ASC
LIMIT 3