我现在有一个查询,它非常适合查找玩家信息(包括他们的排名):
SELECT t1.pid,
t1.type,
t1.pspeed,
t1.distance,
t1.maxspeed,
t1.prestrafe,
t1.strafes,
t1.sync,
t1.wpn,
1+SUM(t2.pid IS NOT NULL) as rank
FROM records t1
LEFT JOIN records t2
ON t1.type = t2.type
AND t1.pspeed = t2.pspeed
AND t1.distance < t2.distance
WHERE t1.pid = "'.$pid.'"
AND t1.type IN ("type1","type2","type3")
GROUP BY t1.type, t1.pspeed
现在的问题是我希望使用 authid
而不是 pid
作为我的变量。我可以在 records
表和 player
表上进行简单的连接,该表的 id
等于 pid
> 在 records
表以及 authid
我希望通过以下方式搜索:
SELECT * FROM records JOIN players ON records.pid=players.id
我希望使用第二个查询来代替第一个查询的 FROM 记录
部分,但由于使用了许多别名,我在尝试中感到困惑。
这是一个可怜的尝试示例:
SELECT t1.pid,
t1.type,
t1.pspeed,
t1.distance,
t1.maxspeed,
t1.prestrafe,
t1.strafes,
t1.sync,
t1.wpn,
1+SUM(t2.pid IS NOT NULL) as rank
FROM (
SELECT *
FROM records
JOIN players ON records.pid=players.id
) t3 t1
LEFT JOIN records t2
ON t1.type = t2.type
AND t1.pspeed = t2.pspeed
AND t1.distance < t2.distance
WHERE t1.authid = "'.$authid.'"
AND t1.type IN ("type1","type2","type3")
GROUP BY t1.type, t1.pspeed
任何能够让我变得更好的人都请随意这样做。我对 SQL 的了解仍然很糟糕。
最佳答案
您的加入看起来非常接近。但是,您为子查询指定了两个别名。只尝试一个
SELECT t1.pid, t1.type, t1.pspeed, t1.distance, t1.maxspeed, t1.prestrafe, t1.strafes, t1.sync, t1.wpn, 1+SUM(t2.pid IS NOT NULL) as rank
FROM
(
SELECT players.*, rec.pid, rec.type, rec.pspeed, rec.distance, rec.maxspeed,
rec.prestrafe, rec.strafes, rec.sync, rec.wpn
FROM records AS rec JOIN players ON rec.pid = players.id ) AS t1
LEFT OUTER JOIN records t2
ON t1.type = t2.type AND t1.pspeed = t2.pspeed AND t1.distance < t2.distance
WHERE t1.authid = "'.$authid.'" AND
t1.type IN ("type1","type2","type3")
GROUP BY t1.type, t1.pspeed
此外,在子查询中命名列应该可以消除重复列错误。
关于mysql - 在连接表而不是实际表上使用查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23282221/