如何在MYSQL中自定义'Order BY'?

时间:2012-09-22 17:27:19

标签: mysql

我有以下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子句条件的前三行的那些符号位于顶部,而仅满足底线的那些位于底部?

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分: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