Tengo un problema con SQL. Quiero hacer la relación de 4 tablas (usuario, appuserFuncitonRelation, organizaciones, GroupCommerce) donde la organización está relacionada con groupCOmmerce y appuserFunctionRelation está relacionado con ambos y con el otro tiene el id de usuario. Lo que quiero hacer es traer el GroupCOmmerce que el usuario no tiene. ¿Cómo se puede hacer eso?
/* Create DB */
Use master;
GO
IF DB_ID (N'JoinsDB3') IS NOT NULL
DROP database JoinsDB3;
CREATE DATABASE JoinsDB3;
GO
Use JoinsDB3;
GO
/*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*/
CREATE TABLE Organizacion(
[ID] [int] NOT NULL,
[Description] [nvarchar](100) NOT NULL);
GO
INSERT INTO [Organizacion] ([ID], [Description])
VALUES (1, 'TestOrg'),(2, 'TestOrg2');
GO
CREATE TABLE [User](
[ID] [int] NOT NULL,
[Description] [nvarchar](100) NOT NULL);
GO
INSERT INTO [User] ([ID], [Description])
VALUES (1, 'admin');
GO
CREATE TABLE CommerceGroup(
[ID] [int] NOT NULL,
[Organization] [int] NOT NULL,
[Description] [nvarchar](100) NOT NULL);
GO
INSERT INTO [CommerceGroup] ([ID], [Organization], [Description])
VALUES (1, 1, 'TestCG'),(2, 1, 'TestCG2'),(3, 1, 'TestCG3'),(4, 1, 'TestCG4');
GO
CREATE TABLE AppUserFunctionsRelation(
[User] [int] NOT NULL,
[Organization] [int] NOT NULL,
[CommerceGroup] [int] NOT NULL);
GO
INSERT INTO AppUserFunctionsRelation ([User], [Organization], [CommerceGroup])
VALUES (1, 1, 1);
GO
/*QUERY*/
SELECT CommerceGroupID FROM (SELECT
[AppUserFunctionsRelation].[user] as userID,
[CommerceGroup].Organization,
[CommerceGroup].ID AS CommerceGroupID ,[CommerceGroup].Description AS CommerceGroupDescription
FROM [AppUserFunctionsRelation]
right JOIN [CommerceGroup] ON CommerceGroup.Organization = AppUserFunctionsRelation.Organization AND AppUserFunctionsRelation.[CommerceGroup] = [CommerceGroup].ID) as Temp
Where Temp.userID IS NULL
tengo eso pero no funciona, gracias.