如何在跨三个表的 mysql 查询中使用联接

How to use joins in a mysql query across three tables

首先是我的桌子:

+----------+      +--------------+     
| users    |      | users_groups |     +--------------+
+----------+      +--------------+     | groups       |
| user_id  |----->| user_id      |     +--------------+
| username |      | group_id     |<----| group_id     |
| realname |      +--------------+     | group_name   |
| password |                           | group_desc   |
+----------+                           +--------------+

从另一个 PHP 脚本我有一个变量 $group_id 现在我想要所有用户名和 user_ids 在这个组 ($group_id).

我试过了,但没用:

SELECT u.username, u.user_id
FROM users u
WHERE users_groups.group_id = $group_id

查询应该是什么样的?有连接的东西,不是吗?

我的PHP-代码:

$group_id = $_POST["group_id"];

    $query_user = mysqli_query($db, 
                                    "SELECT 
                                    User.user_id, User.username
                                    FROM users User 
                                    INNER JOIN user_groups UserGroup
                                        ON User.user_id = UserGroup.user_id
                                    WHERE UserGroup.group_id = $group_id
                                    ");
    while ($row_user = mysqli_fetch_object($query_user)) {
        echo'
        '.$row_user->username.'<br>
        ';
    }

这会起作用:

SELECT u.username, u.user_id
FROM users u
WHERE users_groups.group_id = $group_id && users_groups.user_id = u.user_id
SELECT 
    User.user_id, User.username
FROM users User 
INNER JOIN users_groups UserGroup
    ON User.user_id = UserGroup.user_id
WHERE UserGroup.group_id = $group_id

希望一切顺利!

编辑:

$group_id = mysqli_real_escape_string($db, $_POST["group_id"]);

    $query_user = mysqli_query($db, 
                                    "SELECT 
                                    User.user_id, User.username
                                    FROM users User 
                                    INNER JOIN users_groups UserGroup
                                        ON User.user_id = UserGroup.user_id
                                    WHERE UserGroup.group_id = '$group_id'
                                    ");
    while ($row_user = mysqli_fetch_object($query_user)) {
        echo $row_user->username.'<br>';
    }