-1

'users'、'groups'、'users_groups' の 3 つのテーブルがあります。users と groups テーブルの間の関係は多対多であり、users_groups はその関係を格納します。

 users        users_groups                             groups
 -id (pk)     -user_id(fk references users)            -id (pk)
 -username    -group_id (fk references groups)         -name
 -password 

データ:

users
1. abc
2. admin
3. user
4. tester

Groups
1. testgroup
2. newgroup

Users_groups
group_id    user_id
   1           1
   1           2

グループ 1 (testgroup) ページにいるとしましょう。このグループに属さないすべてのユーザーを取得したい。これどうやってするの?可能であれば、1つのSQLクエリでこれを実行したい

アップデート

SELECT u.username, g.name
FROM users u
LEFT JOIN groups_users ug ON u.id = ug.user_id
LEFT JOIN groups g ON g.id = ug.group_id
WHERE g.id !=1 OR g.id IS NULL
4

2 に答える 2

0

これは簡単なクエリです。

select u.*
from users u
where u.id not in (select user_id from user_groups ug where group_id = 1)

番号ではなく名前で参照する場合:

select u.*
from users u
where u.id not in (select user_id
                   from user_groups ug join
                        groups g
                        on ug.group_id = g.id
                   where g.name = 'testgroup'
                  )
于 2013-03-01T14:11:50.183 に答える
0
SELECT u.username FROM
users u
LEFT JOIN
    users_groups ug ON u.id = ug.user_id,
    groups g ON g.group_id = ug.group_id

WHERE g.name != 'testgroup'
GROUP BY u.username
于 2013-03-01T12:20:05.377 に答える