繁体   English   中英

MySQL select语句从其他两个表中排除字段

[英]MySQL select statement that excludes fields from two other tables

我正在尝试执行查询以查找不是当前用户的“朋友”的所有用户。 例如,如果用户以“ alex”身份登录,我想在users表中显示不是alex(即david)朋友的所有用户。

如果有帮助,我正在使用PHP Codeigniter。 这是我想出的查询(但不返回任何内容):

public function getUser($username) {
    $this->db->query("SELECT username FROM users WHERE username NOT IN 
    (SELECT user1 FROM friendships WHERE user2 = '$username' 
    UNION SELECT user2 FROM friendships WHERE user1 = '$username')");
    return $query->result_array();
}

MySQL表

Users

+----+----------+
| id | username |
+----+----------+
| 1  | alex     |
+----+----------+
| 2  | james    |
+----+----------+
| 3  | david    |
+----+----------+

Friendships

+----+-------+-------+
| id | user1 | user2 |
+----+-------+-------+
| 1  | alex  | james |
+----+-------+-------+
| 2  | james | david |
+----+-------+-------+

您应该将用户ID而不是名称存储在友谊表中。

尝试这个:

select username
from users
where username <> '$username'
    and username not in (
        select case when user1 = '$username' then user2 else user1 end
        from friendships
        where '$username' in (user1, user2)
        )

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM