MySQL – 使用UNION和LIMIT

前端之家收集整理的这篇文章主要介绍了MySQL – 使用UNION和LIMIT前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我注意到了

(SELECT title,relavency,'search1' as source FROM search1
ORDER BY relavency DESC
LIMIT 10)
UNION 
(SELECT title,'search2' as source FROM search2
ORDER BY relavency DESC
LIMIT 10)
ORDER BY relavency DESC 
LIMIT 10

最后一个LIMIT 10不起作用.为什么?

错误

错误代码1064:……在’LIMIT 1000’附近使用”

为什么MysqL workbench会将LIMIT 10检测为LIMIT 1000,但如果它的1000它仍然可以工作?

最佳答案
您可以使用别名嵌套子查询重写您的查询.这应该适合你:

SELECT u.* FROM (
    (SELECT s1.title,s1.relavency,'search1' as source FROM search1 AS s1
    ORDER BY s1.relavency DESC
    LIMIT 10)
        UNION 
    (SELECT s2.title,s2.relavency,'search2' as source FROM search2 AS s2
    ORDER BY s2.relavency DESC
    LIMIT 10)
) AS u ORDER BY u.relavency DESC 
LIMIT 10

仅供参考:您拼错了“相关性”,但我保留了拼写错误,因此查询可以正常工作.

猜你在找的MySQL相关文章