Mysql - 获得最高和最低5个结果

时间:2013-05-03 15:39:57

标签: mysql sql

我有一个查询

SELECT dmn_name AS domain, COUNT(*) AS newsletters, SUM(mwl_sended) AS emailsSent, SUM(IFNULL(nwl_ca, 0)/mwl_sended) * 1000 AS ecpm FROM domain
                JOIN newsletter USING(dmn_id)
                WHERE dmn_actif = 1
                AND nwl_sendedOn > DATE_SUB(NOW(), INTERVAL 1 MONTH)
                AND nwl_sendingEndedOn is NOT NULL
                GROUP BY dmn_name
                ORDER BY ecpm DESC
                LIMIT 5

它返回5个具有最高ecpm的结果。如何修改它以返回最高5和最低5?我想避免两次执行查询。

由于

1 个答案:

答案 0 :(得分:1)

使用UNION ALL

SELECT dmn_name AS domain, COUNT(*) AS newsletters, SUM(mwl_sended) AS emailsSent, SUM(IFNULL(nwl_ca, 0)/mwl_sended) * 1000 AS ecpm FROM domain
                JOIN newsletter USING(dmn_id)
                WHERE dmn_actif = 1
                AND nwl_sendedOn > DATE_SUB(NOW(), INTERVAL 1 MONTH)
                AND nwl_sendingEndedOn is NOT NULL
                GROUP BY dmn_name
                ORDER BY ecpm DESC
                LIMIT 5
UNION ALL
SELECT dmn_name AS domain, COUNT(*) AS newsletters, SUM(mwl_sended) AS emailsSent, SUM(IFNULL(nwl_ca, 0)/mwl_sended) * 1000 AS ecpm FROM domain
                JOIN newsletter USING(dmn_id)
                WHERE dmn_actif = 1
                AND nwl_sendedOn > DATE_SUB(NOW(), INTERVAL 1 MONTH)
                AND nwl_sendingEndedOn is NOT NULL
                GROUP BY dmn_name
                ORDER BY ecpm ASC
                LIMIT 5
ORDER BY ecpm DESC