简体   繁体   English

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

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

I am trying to execute a query to find all users that are not 'friends' of the current user. 我正在尝试执行查询以查找不是当前用户的“朋友”的所有用户。 For example, if the user is logged in as 'alex', I want to display all users in the users table that are not friends of alex (ie david). 例如,如果用户以“ alex”身份登录,我想在users表中显示不是alex(即david)朋友的所有用户。

I'm using PHP Codeigniter if that helps. 如果有帮助,我正在使用PHP Codeigniter。 This is the query I came up with (but it returns nothing): 这是我想出的查询(但不返回任何内容):

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 Tables MySQL表

Users

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

Friendships

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

You should've stored the user id in friendship table instead of names. 您应该将用户ID而不是名称存储在友谊表中。

Try this: 尝试这个:

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