如何在UNION mysql查询中使用ORDER BY和LIMIT

时间:2012-10-02 04:09:13

标签: mysql union

我有一点问题,我有一个像这样的MySQL查询代码:

SELECT a.id, b.name AS itemName, b.slug AS itemSlug FROM table_idx a
INNER JOIN table_product b ON b.id = a.targetid AND a.target='PRODUCT'
WHERE a.memberid=$memberid
UNION
SELECT a.id, c.name AS itemName, c.slug AS itemSlug FROM table_idx a
INNER JOIN table_news c ON c.id = a.targetid AND a.target='NEWS'
WHERE a.memberid=$memberid
UNION
SELECT a.id, d.name AS itemName, d.slug AS itemSlug FROM table_idx a
INNER JOIN table_promo d ON d.id = a.targetid AND a.target='PROMO'
WHERE a.memberid=$memberid

如何在上面的查询中添加ORDER BY a.id DESC LIMIT 0,10?谢谢你的帮助。

2 个答案:

答案 0 :(得分:3)

除非您的意图是在ORDER BY之前的每个查询LIMITUNION,否则只需添加

ORDER BY id DESC LIMIT 0,10

在查询的底部。

答案 1 :(得分:3)

用另一个选择包裹它。

SELECT * FROM (
SELECT a.id, b.name AS itemName, b.slug AS itemSlug FROM table_idx a
INNER JOIN table_product b ON b.id = a.targetid AND a.target='PRODUCT'
WHERE a.memberid=$memberid
UNION
SELECT a.id, c.name AS itemName, c.slug AS itemSlug FROM table_idx a
INNER JOIN table_news c ON c.id = a.targetid AND a.target='NEWS'
WHERE a.memberid=$memberid
UNION
SELECT a.id, d.name AS itemName, d.slug AS itemSlug FROM table_idx a
INNER JOIN table_promo d ON d.id = a.targetid AND a.target='PROMO'
WHERE a.memberid=$memberid
) AS t ORDER BY t.id DESC LIMIT 0,10