首先是我的桌子:
game
+----+--------------+
| id | game |
+----+--------------+
| 1 | Game1 |
| 2 | Game2 |
| 4 | Game4 |
+----+--------------+
group_game
+---------+----------+
| game_id | group_id |
+---------+----------+
| 1 | 33 |
| 1 | 45 |
| 4 | 33 |
+---------+----------+
groups
+----+------------+----
| id | group_name | ...
+----+------------+----
| 33 | Group33 | ...
| 45 | Group45 | ...
+----+------------+----
users
+---------+----------+----
| user_id | username | ...
+---------+----------+----
| 1 | User1 | ...
| 2 | User2 | ...
+---------+----------+----
users_groups
+---------+----------+
| user_id | group_id |
+---------+----------+
| 1 | 33 |
| 1 | 45 |
| 2 | 45 |
+---------+----------+
我想做什么
现在我想检查当前用户是否在一个播放" Game4"如果是,则输出应为id和组的名称。
users
)users_groups
)groups
)group_game
)game
)我当前的代码(不给我任何行)
$user_id = $_SESSION["user_id"];
$Game4= "Game4";
$gruppen_dayz = $db->prepare("
SELECT g.group_id, g.group_name
FROM groups g
LEFT JOIN users_groups ug
ON g.group_id = ug.group_id
LEFT JOIN group_game gg
ON g.group_id = gg.group_id
LEFT JOIN game ga
ON ga.id = gg.game_id
WHERE ga.game = ? AND ug.user_id = ?
");
$gruppen_dayz->bind_param('ii', $Game4, $user_id);
我不确切知道应该如何构建此查询:/
答案 0 :(得分:0)
在连接生成数据集后应用了where子句,否定了连接的左连接方面。要解决此问题,请将标准移动到连接本身,以便在连接之前应用限制。否则,您的左连接中生成的NULL值将被where子句排除。
也可能有其他元素,这只是我看到的第一个元素。
$user_id = $_SESSION["user_id"];
$Game4= "Game4";
$gruppen_dayz = $db->prepare("
SELECT g.group_id, g.group_name
FROM groups g
LEFT JOIN users_groups ug
ON g.group_id = ug.group_id
AND ug.user_id = ?
LEFT JOIN group_game gg
ON g.group_id = gg.group_id
LEFT JOIN game ga
ON ga.id = gg.game_id
AND ga.game = ?
");
$gruppen_dayz->bind_param('ii', $Game4, $user_id);
---更新---- 经过进一步调查,我认为你的加入是错误的。根据您的表结构,组没有group_ID字段。现在走过其余的......
SELECT g.group_id, g.group_name
FROM groups g
LEFT JOIN users_groups ug
ON g.id = ug.group_id
LEFT JOIN group_game gg
ON g.id = gg.group_id
LEFT JOIN game ga
ON ga.id = gg.game_id
WHERE ga.game = ? AND ug.user_id = ?
我可能会把它重写为......
SELECT G.Id, G.Group_name
FROM USERS_GROUPS UG
INNER JOIN GROUPS G
on UG.Group_ID = G.ID
INNER JOIN GROUP_GAME GG
on GG.Group_ID = G.ID
INNER JOIN Game GA
on GA.ID = GG.Game_ID
WHERE ga.game = ? AND ug.user_id = ?
根据您的标准,我认为左边连接没有价值或需要。