0

userscontacts、およびの3 つのテーブルがありgroupsます。ユーザーのすべての連絡先を検索し、選択した連絡先からgroup_idgroupsテーブルに特定の連絡先があるそのユーザーの連絡先を除外したいと考えています。

groupsのテーブルは次のように構成されています。

id (primary key)
group_id (a foreign key to a table contain general group info)
user_id (a foreign key to the users table)

contactsのテーブルは次のように構成されています。

id (primary key)
user_id (a foreign key to the `users` table of the user who added the contact)
contact_id (a foreign key to the `users` table of the added contact)

現在、機能していないクエリは次のとおりです。

"""SELECT c.*, u.*
   FROM contacts c
       LEFT JOIN groups g ON c.contact_id = g.user_id
       INNER JOIN users u on u.id = c.contact_id
   WHERE c.user_id = %s AND
       <not sure what further constraints to place on query>""", (user_id, group_id)

私の理解では、は確かに正しくありません。それが正しくないことを考えると、句LEFT JOINにこれ以上の制約をまだ追加していません。WHERE

これを達成するための最良の方法は何ですか?ありがとうございました。

4

1 に答える 1

1

LEFT JOINが正しく、どのグループにも属さない連絡先を含めたいと仮定すると、次のクエリを試すことができます。

select 
    c.*,
    u.*
from users u
    join contacts c
        on u.id = c.user_id
    left join groups g
        on c.contact_id = g.user_id
where
    c.user_id = %s
    and g.group_id not in (<your groups here>)

グループのリストは、コンマ区切りの識別子のリストになります。PostgreSQL python ドライバーにこれを簡単にフォーマットするための関数が含まれているかどうかはわかりませんが、それがアイデアです。

コメントの二次的な質問 (グループのない連絡先と除外されたグループの連絡先を取得する方法) に答えるには、おそらくユニオンを使用する必要があります。

select 
    c.*,
    u.*
from users u
    join contacts c
        on u.id = c.user_id
    left join groups g
        on c.contact_id = g.user_id
where
    c.user_id = %s
    and g.group_id is null
union
select 
    c.*,
    u.*
from users u
    join contacts c
        on u.id = c.user_id
    join groups g
        on c.contact_id = g.user_id
where
    c.user_id = %s
    and g.group_id = %d
于 2013-11-12T19:03:18.087 に答える