Mysql 对联接表而不是实际表使用查询
我现在有一个查询,它非常适合查找玩家信息,包括他们的排名:Mysql 对联接表而不是实际表使用查询,mysql,sql,Mysql,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
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
我希望使用第二个查询来代替第一个查询中的FROM records部分,但由于使用了许多别名,我在尝试中把自己弄糊涂了
下面是一个令人遗憾的尝试例子:
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
此外,在子查询中命名列应该可以消除重复列错误。这行似乎有问题:SELECT*FROM records JOIN players ON records.pid=players.id t3 t1发布您收到的错误消息。这让我很害怕:其中t1.pid='.$pid'。它说您正在构建的查询极易受到sql注入攻击:我得到了一个重复的列名id错误。这就是我尝试使用两个别名的原因。记录是否有ID列?有两个ID列通过,查询引擎无法识别哪个是哪个。必须为其中一个设置别名,或将其从“选择列”列表中删除。
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