简体   繁体   中英

M:N relation an query

i've some problems with a specific mysql query an an specific construct.
There are 2 tables:

table users (id, username)
table groups (id, groupname)

these 2 tables are in an m:n relation, but there are 2 tables for that.

First in maps user to groups

table usertogroups (idmaster, idslave)  

where idmaster is related to users.id and idslave is related groups.id

Second maps groups to users

table groupstouser (idmaster, idslave)  

where idmaster is related to groups.id an idslave is related to users.id

Depend on the application it could not be changed.

Now i want to get all groups with the depending users in one query with the relation of both table, groupstouser and usertogroups.
I've tried al lot of statements, but if I take the second table in it doesn't work.

Any helpfull Ideas?

Use this as an inline view to get the data from both association tables :

((SELECT idmaster AS userid, idslave AS groupid FROM userstogroup)
UNION
(SELECT idslave AS userid, idmaster AS groupid FROM groupstouser)) all_associations

Then you can query like this :

SELECT groups.groupname, users.username
FROM groups
INNER JOIN ((SELECT idmaster AS userid, idslave AS groupid FROM userstogroup)
            UNION
           (SELECT idslave AS userid, idmaster AS groupid FROM groupstouser)) all_associations
ON groups.id =  all_associations.groupid
INNER JOIN users
ON users.id =  all_associations.userid

And here's an SQL Fiddle .

I am not sure, it might solve your problem:

(SELECT * FROM usertogroups  WHERE idmaster=10)
UNION
(SELECT * FROM groupstouser  WHERE idslave=10)

I think your database design is wrong.

When a user is assigned to a group only single table can be used for it. You must be saving duplicate records in both usertogroups and groupstouser .

Try to get your data from only single table.

SELECT * FROM usertogroups order by idslave

If I am wrong that you are not saving duplicate data in both the tables, then specify reason of having two tables

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM