簡體   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