2015-05-13 154 views
1

我试图执行这个查询:如何使用MySQL UNION内UNION ALL

(
SELECT co.id as offerId, co.title, co.details, co.link, co.reference, co.rank 
FROM club_offer co 
WHERE co.id IN (31, 791, 360, 382) 
GROUP BY offerId 
UNION 
SELECT co.id as offerId, co.title, co.details, co.link, co.reference, co.rank 
FROM club_offer co 
WHERE co.id IN (869, 376, 201, 1246) 
GROUP BY offerId 
ORDER BY rank DESC 
) 
UNION ALL 
(
SELECT co.id as offerId, co.title, co.details, co.link, co.reference, co.rank 
FROM club_offer co 
WHERE co.id IN (117, 168, 193, 204, 330, 377, 378, 379, 380, 381, 452, 931, 980, 1100, 1146, 1147, 1190, 1247) 
GROUP BY offerId 
ORDER BY rank DESC 
) 

,但我得到的错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UNION

所以,我想,要么我使用错误的语法或我正在尝试做一些无法完成的事情。我猜这个SQL小提琴不需要这个,很有可能有经验的人会马上看到什么是错的。

有人可以帮忙吗?谢谢

+0

删除'ORDER BY's – Lamak

+0

没有帮助..... –

+2

为什么GROUP BY时,没有聚合函数被使用?此外,MySQL可以在GROUP BY中使用别名吗? – jarlh

回答

2

您的错误来自您的括号。这里有一种方法来重写你的当前查询:

SELECT offerId, title, details, link, reference, rank 
FROM 
(
    SELECT co.id as offerId, co.title, co.details, co.link, co.reference, co.rank 
    FROM club_offer co 
    WHERE co.id IN (31, 791, 360, 382) 
    UNION 
    SELECT co.id as offerId, co.title, co.details, co.link, co.reference, co.rank 
    FROM club_offer co 
    WHERE co.id IN (869, 376, 201, 1246) 
) t 
UNION ALL 
SELECT co.id as offerId, co.title, co.details, co.link, co.reference, co.rank 
FROM club_offer co 
WHERE co.id IN (117, 168, 193, 204, 330, 377, 378, 379, 380, 381, 
       452, 931, 980, 1100, 1146, 1147, 1190, 1247) 
ORDER BY rank DESC 

我已经删除从内部查询group byorder by条款,以及 - 随时根据需要加回,但子查询中的order by将毫无用处。

+0

它的作品,非常感谢你! –

0

您正在以错误的方式使用parentesis:您放入代码的方式似乎是您尝试在选择unioned statmets之间建立优先顺序,而这是语法所不允许的。但因为是由提及的评析某人时,你可以:

select * from 
    (select ... from ... 
    union 
    select ... from ...) as T1 
union all 
    select ... from ... 

凡工会/工会的各方面都是单queryes。

一些小问题:
order by如果没有限制子句存在,每个select中都没有意义。
不是在所有情况下group by(用mysql hability错过分组功能)会导致同样的结果distinct