MySQL union,join&限制

时间:2013-11-24 13:33:48

标签: mysql sql limit union

我有以下查询:

SELECT result.globalId AS id, result.date, p1.playerName AS player, p2.playerName AS   target, w.weaponIngameName AS weapon, result.headshot, s.serverName AS server, result.origin
FROM (
(

SELECT globalId, date, serverId, playerId, targetId, weaponId, headshot, 'playerkills' AS origin
FROM playerkills
WHERE (
playerkills.playerId =976
OR playerkills.targetId =976
)
ORDER BY date DESC
)
UNION (

SELECT globalId, date, serverId, playerId, NULL , NULL , NULL , 'playersuicides' AS origin
FROM playersuicides
WHERE (
playersuicides.playerId =976
)
ORDER BY date DESC
)
)result
LEFT JOIN players p1 ON result.playerId = p1.playerId
LEFT JOIN players p2 ON result.targetId = p2.playerId
LEFT JOIN weapons w ON result.weaponId = w.weaponId
LEFT JOIN servers s ON result.serverId = s.serverId
ORDER BY result.date DESC , result.globalId DESC

我希望在应用任何result之前限制JOIN联合最多包含300个结果。我该如何做到这一点?

仅在LIMIT 300之后添加(...) result不起作用,它会出现以下MySQL错误: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 'LEFT JOIN players p1 ON result.playerId = p1.playerId LEFT JOIN players p2 ON r' at line 9

1 个答案:

答案 0 :(得分:0)

将查询更改为以下内容时,它确实有效:

SELECT result.globalId AS id, result.date, p1.playerName AS player, p2.playerName AS   target, w.weaponIngameName AS weapon, result.headshot, s.serverName AS server, result.origin
FROM (
(

SELECT globalId, date, serverId, playerId, targetId, weaponId, headshot, 'playerkills' AS origin
FROM playerkills
WHERE (
playerkills.playerId =976
OR playerkills.targetId =976
)
ORDER BY date DESC
)
UNION (

SELECT globalId, date, serverId, playerId, NULL , NULL , NULL , 'playersuicides' AS origin
FROM playersuicides
WHERE (
playersuicides.playerId =976
)
ORDER BY date DESC
) ORDER BY date DESC LIMIT 300) result
LEFT JOIN players p1 ON result.playerId = p1.playerId
LEFT JOIN players p2 ON result.targetId = p2.playerId
LEFT JOIN weapons w ON result.weaponId = w.weaponId
LEFT JOIN servers s ON result.serverId = s.serverId
ORDER BY result.date DESC , result.globalId DESC

请注意,我在调用表ORDER BY date DESC LIMIT 300之前添加了result,所以现在大致发生以下情况:

1)正在运行SELECT内的UNION个人。

2)UNION用于组合结果。

3)ORDER BYLIMIT正在应用于UNION

4)UNION被命名为result

5)查询的其余部分发生。