我正在尝试执行查询以查找不是当前用户“朋友”的所有用户。例如,如果用户以'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 |
+----+-------+-------+
答案 0 :(得分:1)
您应该将用户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)
)