简体   繁体   English

M:N关系查询

[英]M:N relation an query

i've some problems with a specific mysql query an an specific construct. 我在使用特定的mysql查询和特定的结构时遇到了一些问题。
There are 2 tables: 有2个表:

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

these 2 tables are in an m:n relation, but there are 2 tables for that. 这2个表处于m:n关系中,但是有2个表。

First in maps user to groups 首先将用户映射到组

table usertogroups (idmaster, idslave)  

where idmaster is related to users.id and idslave is related groups.id 其中idmaster与users.id相关,而idslave与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 其中idmaster与groups.id相关,而idslave与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. 现在,我想在一个查询中使用表,groupstouser和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 . 这是一个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. user分配给group只能将单个表用于该组。 You must be saving duplicate records in both usertogroups and groupstouser . 您必须将重复记录保存在usertogroupsgroupstouser

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 如果我错了,您没有在两个表中都保存重复数据,请指定具有两个表的原因

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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