0

我有一个查询

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 个最低?我想避免两次执行查询。

谢谢

4

1 回答 1

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
于 2013-05-03T15:41:26.667 回答