我遇到SQL问题,我想在关系4表(user,appuserFunctionRelation,organizations,GroupCommerce)中进行,其中组织与GroupCommerce相关,appuserFunctionRelation与两者相关,而另一个与用户ID相关。< / p>
我想要做的是带上用户没有的GroupCommerce。我怎么能这样做?
SELECT
[AppUserFunctionsRelation].[user],
[CommerceGroup].Organization,
[CommerceGroup].ID AS CommerceGroupID ,
[CommerceGroup].Description AS CommerceGroupDescription
FROM [AppUserFunctionsRelation]
RIGHT JOIN [CommerceGroup]
ON CommerceGroup.Organization = AppUserFunctionsRelation.Organization
AND AppUserFunctionsRelation.[GroupCommerce] = [CommerceGroup].ID
WHERE AppUserFunctionsRelation.GroupCommerce IS NULL
AND CommerceGroup.Organization IN ( SELECT Organizations.[ID]
FROM AppUserFunctionsRelation
INNER JOIN Organizations
ON Organizations.ID = AppUserFunctionsRelation.Organization
WHERE AppUserFunctionsRelation.[User] =22
)
表:
User
ID|Description
1 |admin
Organization
ID|Description
1 |TestOrg
2 |TestOrg2
CommerceGroup
ID|Organization|Description
1 |1 |TestGC
2 |1 |TestGC2
3 |1 |TestGC3
4 |2 |TestGC4
AppUserFunctionsRelation
User|organization|CommerceGroup
1 |1 |1
预期结果
user|organization|commercegroup
1 | 1 |2
1 | 1 |3
如果您拥有该组织的所有业务组,它将是这样的
AppUserFunctionsRelation
User|organization|CommerceGroup
1 |1 |0
有点过头但是我需要这样, 与0我意识到用户拥有该组织的所有贸易组 id 1
我想将该组织的用户与
无关的交易组带到谢谢
答案 0 :(得分:0)
我很确定你想要这样的东西。我对列名做了一些假设。如果你真的在每个表中都有名称ID,我会敦促你解决这个问题。 OrganizationID不是突然只是一个ID,因为它在Organization表中。是的,这有点多余,但是在表格中更改名称的列很难配合使用。
这应该可以解释我的问题。
select *
from Users u
join Organization o on o.OrganizationID = u.UserID
join AppUserFunctionsRelation r on r.UserID = u.UserID and r.OrganizationID = o.OrganizationID
left join CommerceGroup cg on cg.OrganizationID = r.OrganizationID
where u.UserID = 1
and cg.OrganizationID is null
- 编辑 -
我认为你可以做这样的事情来删除Users表。结果应该几乎相同,但现在这似乎没用了,因为你得到的所有用户都是一个数字。难以识别那样的人。
select *
from Organization o
join AppUserFunctionsRelation r on r.OrganizationID = o.OrganizationID
left join CommerceGroup cg on cg.OrganizationID = r.OrganizationID
where cg.OrganizationID is null
答案 1 :(得分:-1)
它不会起作用
select *
from AppUserFunctionsRelation r
join Organizations or on r.Organization = o.ID
join CommerceGroup cg on cg.Organization = r.Organization
where r. [User] = 37
我带了用户关联的CommerceGroup,我需要的是将没有关联的GC带到特定组织