查询SQL限制

时间:2016-02-13 02:18:32

标签: mysql left-join

TABLES

PLAYERS

id | name    | rank id
1  | player1 | 3
2  | player2 | 0
3  | player3 | 0
4  | player4 | 1
5  | player5 | 0
6  | player6 | 0

GUILDS

id | name
1  | test1
2  | test2

GUILD RANKS

id | guild_id
1  |  1 <- which is test
2  |  2 <- which is test2

QUERY

$player = query -> name
$player_id = $SQL->query('SELECT rank_id from players where name = "'.htmlspecialchars($player['name']).'"')->fetch();
$player_id = $player_id['rank_id'];
$has_guild = $SQL->query('SELECT guild_id from guild_ranks where id = '. $player_id .'')->fetch();
$has_guild = $has_guild['guild_id'];
if($has_guild == 0){
    $guild_d_player = "No Guild";
}else{
    $guild_do_player = $SQL->query('SELECT name from guilds where id = '.$has_guild.' > 0')->fetch();
    $guild_do_player = $guild_do_player ['name'];
    $guild_d_player = "";
}

这就是这个:

这是关于公会。

示例:

Name    |   Guild Name   | This player truly is in a guild?

Player1 |      Test      | Yes

Player2 |  TestNo Guild  | <- Here is the problem, this player doesn't have guild but seems like if he was on one.

Player3 |  TestNo Guild  | No

Player4 |      Test2     | Yes

Player5 |  Test2No Guild | No

Player6 |  Test2No Guild | No

Etc...

重复公会名称,直到查询获得真正存在的新公会名称。

完整查询:http://pastebin.com/03TYv9V9

1 个答案:

答案 0 :(得分:2)

您应该使用left joins连接3个表的单个查询:

SELECT g.name from players p
left join guild_ranks gr on p.rank_id=gr.id
left join guilds g on g.id=gr.guild_id
where name=...

如果返回的值为空(null),则播放器没有公会。

补充说明:

  1. 您不应该通过播放器查询此信息。您应该将此查询与您在pastebin中的代码顶部的主查询结合起来。只需将其中使用的逗号语法更改为显式连接。

  2. 您提供的样本数据与预期结果不一致。 Player1有3作为rank_id,但在id = 3的guild_rank表中没有记录,但根据经过验证的结果,该玩家处于test1公会。

  3. 我不明白使用guild_rank表以及为什么要将玩家链接到该表而不是将guild_id存储在玩家表中。