在连接表而不是实际表上使用查询

时间:2014-04-25 00:34:11

标签: 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 
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 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感到害怕。

1 个答案:

答案 0 :(得分:1)

你的加入看起来非常接近。但是,您为子查询提供了两个别名。试试一下

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

此外,在子查询中命名列应该可以消除重复的列错误。