1

我有以下mysql查询:

SELECT merchantNames.strippedName,merchantNames.lastCached,merchantNames.id
FROM merchantNames 
JOIN autoCoupons  
ON merchantNames.rawName = autoCoupons.merchantName
WHERE NOW() > autoCoupons.startDate AND autoCoupons.startDate > merchantNames.lastCached
OR NOW() > autoCoupons.endDate AND autoCoupons.endDate > merchantNames.lastCached
OR NOW() > autoCoupons.timeAdded AND autoCoupons.timeAdded > merchantNames.lastCached
OR merchantNames.lastCached < NOW() - INTERVAL 2 DAY
GROUP BY merchantNames.strippedName
ORDER BY merchantNames.pageviews DESC

如何设置此查询以使满足 WHERE 子句条件前三行的结果位于顶部,而仅满足底线的结果位于底部的方式对结果进行排序?

4

2 回答 2

3

将查询一分为二并使用 UNION 将结果连接在一起。

于 2012-09-22T17:30:04.387 回答
1

还有其他方法可以获得查询所需的结果,但对于“自定义ORDER BY”,您可以按布尔子句的结果排序。DESC将 true (1) 结果放在第一位,false (0) 结果放在第二位。在您的情况下,使用嵌套(如下)读取和写入此查询是最容易的SELECT,但当然您可以使用 ORDER BY 中的显式条件编写更长的查询,这可能会更快。

SELECT r.strippedName, r.lastCached, r.id
FROM
    (SELECT
        merchantNames.strippedName,
        merchantNames.lastCached,
        merchantNames.id,
        merchantNames.pageviews,
        (NOW() > autoCoupons.startDate AND autoCoupons.startDate > merchantNames.lastCached) AS a,
        (NOW() > autoCoupons.endDate AND autoCoupons.endDate > merchantNames.lastCached) AS b,
        (NOW() > autoCoupons.timeAdded AND autoCoupons.timeAdded > merchantNames.lastCached) AS c,
        (merchantNames.lastCached < NOW() - INTERVAL 2 DAY) AS d
    FROM merchantNames 
    JOIN autoCoupons ON merchantNames.rawName = autoCoupons.merchantName
    GROUP BY merchantNames.strippedName) AS r
WHERE r.a OR r.b OR r.c OR r.d
ORDER BY (r.a OR r.b OR r.c) DESC, pageviews DESC
于 2012-09-22T17:36:00.703 回答