[英]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.