MySQL - UNION ALL 在同一个表上查询

bel*_*lek 3 mysql union alias

我想使用我在网站上找到的一些查询- 我根据自己的目的对其进行了调整:

SELECT * FROM 
(
(
SELECT id, lng FROM stations WHERE lng >= 18.123 ORDER BY lng LIMIT 1
) AS result1
UNION ALL
(
SELECT id, lng FROM stations WHERE lng < 18.123 ORDER BY lng LIMIT 1
) AS result2
)
ORDER BY abs(18.123-lng) LIMIT 1;
Run Code Online (Sandbox Code Playgroud)

但我有一个错误 Syntax error, unexpected AS, expecting UNION_SYM or ')'

当我尝试不使用别名时,我(显然)不断收到错误 Error Code: 1248. Every derived table must have its own alias

你能帮我弄清楚我做错了什么吗?先感谢您。

VH-*_*NZZ 5

您需要为最外面的表设置别名,例如:

SELECT * FROM 
(
    (SELECT id, lng FROM stations WHERE lng >= 18.123 ORDER BY lng LIMIT 1)
    UNION ALL
    (SELECT id, lng FROM stations WHERE lng < 18.123 ORDER BY lng LIMIT 1)
) AS result12
ORDER BY abs(18.123-lng) LIMIT 1;
Run Code Online (Sandbox Code Playgroud)

编辑:忘记了内部查询周围的括号。