我有以下表格
id name categoryid status isdelete start_date end_date showorder
SELECT *
FROM product
WHERE isdelete = 0
AND status = 1
AND name LIKE '%%'
AND categoryid = 4
ORDER
BY showorder ASC
现在我想绑定像
这样的数据1) start_date 和 end_date 的数据介于今天的日期之前
2)其余数据将使用 showorder 按字段
排序那么如何使用一个查询实现这一点,因为后来我必须实现分页,所以双重查询不适合
答案 0 :(得分:2)
您可以在ORDER BY
中拥有多个密钥,包括表达式:
SELECT p.*
FROM product p
WHERE p.isdelete = '0' AND p.status = 1 AND
p.name LIKE '%%' AND categoryid = '4'
ORDER BY (CASE WHEN getdate() BETWEEN start_date AND end_date THEN 1 ELSE 2 END),
showorder ASC
答案 1 :(得分:0)
我们可以在ORDER BY AS之后使用多个字段:
SELECT * FROM product WHERE isdelete = '0' AND status = 1 AND name LIKE '%%'
AND categoryid = '4' ORDER BY start_date DESC,end_date DESC,showorder ASC