473,883 Members | 1,692 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Many to Many to Many SQL Query

I have 3 data tables, A, B and C, with many to many relationship
tables between A-B and A-C.

The data in A and C changes rarely, and the A-C relationship relates
all possible combinations of A to a C

If A contains A.1 to A.3 and C contains C.1 - C.8 then A-C could
contain the records:

A.1, C.1
A.2, C.2
A.3, C.3
A.1, C.4
A.2, C.4
A.1, C.5
A.3, C.5
A.2, C.6
A.3, C.6
A.1, C.7
A.2, C.7
A.3, C.7

so that any set of records from A (including the empty set) relates to
exactly on record in C

and suppose that B contains records from B.1 to B.3, and A-B contains
records
A.2, B.1
A.1, B.2
A.3, B.2

What I am having touble doing is crafting a query that will take me
from a record in B to the record in C that has the corrisponding set
of records in A-C as is in A-B for the chosen B.

ie, I want a query that will give me a result set something like

B.1, C.2
B.2, C.5
B.3, C.8

As far as I can come up with, this is not doable in a single query,
but perhaps I am missing something....

Simon Withers
Jul 20 '05 #1
9 13714
Please post DDL (CREATE TABLE statements) for these tables - simplified if
possible but including keys and constraints. Also post some sample data as
INSERT statements. It will save you a lot of typing and make it easier for
others to understand your problem.

--
David Portas
------------
Please reply only to the newsgroup
--
Jul 20 '05 #2
Create/Insert scripts:

CREATE TABLE [Product] (
[ProductID] [int] NOT NULL ,
[Name] [char] (10) COLLATE Compatibility_5 2_409_30003 NULL ,
CONSTRAINT [PK_Product] PRIMARY KEY CLUSTERED
(
[ProductID]
) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [Project] (
[ProjectID] [int] NOT NULL ,
[Name] [char] (10) COLLATE Compatibility_5 2_409_30003 NULL ,
CONSTRAINT [PK_Project] PRIMARY KEY CLUSTERED
(
[ProjectID]
) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [ProjectProduct] (
[ProjectID] [int] NOT NULL ,
[ProductID] [int] NOT NULL ,
CONSTRAINT [PK_ProjectProdu ct] PRIMARY KEY CLUSTERED
(
[ProjectID],
[ProductID]
) ON [PRIMARY] ,
CONSTRAINT [FK_ProjectProdu ct_Product] FOREIGN KEY
(
[ProductID]
) REFERENCES [Product] (
[ProductID]
) ON DELETE CASCADE ON UPDATE CASCADE ,
CONSTRAINT [FK_ProjectProdu ct_Project] FOREIGN KEY
(
[ProjectID]
) REFERENCES [Project] (
[ProjectID]
) ON DELETE CASCADE ON UPDATE CASCADE
) ON [PRIMARY]
GO
CREATE TABLE [SubledgerID] (
[SubledgerID] [int] NOT NULL ,
[Name] [char] (10) COLLATE Compatibility_5 2_409_30003 NULL ,
CONSTRAINT [PK_SubledgerID] PRIMARY KEY CLUSTERED
(
[SubledgerID]
) ON [PRIMARY]
) ON [PRIMARY]
GO
CREATE TABLE [SubledgerProduc t] (
[SubledgerID] [int] NOT NULL ,
[ProductID] [int] NOT NULL ,
CONSTRAINT [PK_SubledgerPro duct] PRIMARY KEY CLUSTERED
(
[SubledgerID],
[ProductID]
) ON [PRIMARY] ,
CONSTRAINT [FK_SubledgerPro duct_Product] FOREIGN KEY
(
[ProductID]
) REFERENCES [Product] (
[ProductID]
) ON DELETE CASCADE ON UPDATE CASCADE ,
CONSTRAINT [FK_SubledgerPro duct_SubledgerI D] FOREIGN KEY
(
[SubledgerID]
) REFERENCES [SubledgerID] (
[SubledgerID]
) ON DELETE CASCADE ON UPDATE CASCADE
) ON [PRIMARY]
GO

INSERT INTO [Product] ([ProductID], [Name]) VALUES (1, 'Product A')
INSERT INTO [Product] ([ProductID], [Name]) VALUES (2, 'Product B')
INSERT INTO [Product] ([ProductID], [Name]) VALUES (3, 'Product C')

INSERT INTO [Project] ([ProjectID], [Name]) VALUES (1, 'Project 1')
INSERT INTO [Project] ([ProjectID], [Name]) VALUES (2, 'Project 2')
INSERT INTO [Project] ([ProjectID], [Name]) VALUES (3, 'Project 3')

INSERT INTO [SubledgerID] ([SubledgerID], [Name]) VALUES (1, 'Subl a')
INSERT INTO [SubledgerID] ([SubledgerID], [Name]) VALUES (2, 'Subl b')
INSERT INTO [SubledgerID] ([SubledgerID], [Name]) VALUES (3, 'Subl c')
INSERT INTO [SubledgerID] ([SubledgerID], [Name]) VALUES (4, 'Subl d')
INSERT INTO [SubledgerID] ([SubledgerID], [Name]) VALUES (5, 'Subl e')
INSERT INTO [SubledgerID] ([SubledgerID], [Name]) VALUES (6, 'Subl f')
INSERT INTO [SubledgerID] ([SubledgerID], [Name]) VALUES (7, 'Subl g')
INSERT INTO [SubledgerID] ([SubledgerID], [Name]) VALUES (8, 'Subl h')

INSERT INTO [ProjectProduct] ([ProjectID], [ProductID]) VALUES (1, 3)
INSERT INTO [ProjectProduct] ([ProjectID], [ProductID]) VALUES (2, 1)
INSERT INTO [ProjectProduct] ([ProjectID], [ProductID]) VALUES (2, 3)

INSERT INTO [SubledgerProduc t] ([SubledgerID], [ProductID]) VALUES (1,
1)
INSERT INTO [SubledgerProduc t] ([SubledgerID], [ProductID]) VALUES (2,
2)
INSERT INTO [SubledgerProduc t] ([SubledgerID], [ProductID]) VALUES (3,
3)
INSERT INTO [SubledgerProduc t] ([SubledgerID], [ProductID]) VALUES (4,
1)
INSERT INTO [SubledgerProduc t] ([SubledgerID], [ProductID]) VALUES (4,
2)
INSERT INTO [SubledgerProduc t] ([SubledgerID], [ProductID]) VALUES (5,
2)
INSERT INTO [SubledgerProduc t] ([SubledgerID], [ProductID]) VALUES (5,
3)
INSERT INTO [SubledgerProduc t] ([SubledgerID], [ProductID]) VALUES (6,
1)
INSERT INTO [SubledgerProduc t] ([SubledgerID], [ProductID]) VALUES (6,
3)
INSERT INTO [SubledgerProduc t] ([SubledgerID], [ProductID]) VALUES (7,
1)
INSERT INTO [SubledgerProduc t] ([SubledgerID], [ProductID]) VALUES (7,
2)
INSERT INTO [SubledgerProduc t] ([SubledgerID], [ProductID]) VALUES (7,
3)
Desired Output:

SELECT Project.Name, Project.Project ID, SubledgerID.Nam e,
SubledgerID.Sub ledgerID FROM ?????

Producing:

Project 1, 1, Subl c, 3
Project 2, 2, Subl f, 6
Project 3, 3, Subl h, 8

Simon Withers
*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 20 '05 #3
try this script

SELECT Project.Name, Project.Project ID, SubledgerID.Nam e,
SubledgerID.Sub ledgerID FROM Project , SubledgerID , ProjectProduct,
SubledgerProduc t WHERE SubledgerProduc t.ProductID IN
( SELECT ProjectProduct. ProductID FROM ProjectProduct WHERE
ProjectProduct. ProjectID = Project.Project ID )
AND SubledgerID.Sub ledgerID=Subled gerProduct.Subl edgerID GROUP BY
Project.Name, Project.Project ID, SubledgerID.Nam e,
SubledgerID.Sub ledgerID

it will produce

Project 1 1 Subl c 3
Project 1 1 Subl e 5
Project 1 1 Subl f 6
Project 1 1 Subl g 7
Project 2 2 Subl a 1
Project 2 2 Subl c 3
Project 2 2 Subl d 4
Project 2 2 Subl e 5
Project 2 2 Subl f 6
Project 2 2 Subl g 7

is it ok?
--
..bucho
ICQ#: 38153136
Distributed.net RC5-72
ID: su*****@1580.ru

Jul 20 '05 #4
I'm not sure I've understood your requirement correctly, but does this help:

SELECT DISTINCT PR.name, PR.projectid, SL.name, SL.subledgerid
FROM Project AS PR
JOIN ProjectProduct AS PP
ON PP.projectid = PR.projectid
JOIN SubLedgerProduc t AS SP
ON SP.productid = PP.productid
JOIN SubLedgerID AS SL
ON SL.subledgerid = SP.subledgerid

--
David Portas
------------
Please reply only to the newsgroup
--
Jul 20 '05 #5
[posted and mailed, please reply in news]

What a devilish problem! Took me quite some time understand what you
are looking for!

What I am offering is only a partial solution, and may even prove to be
a non-solution. It looks like this:

SELECT a.SubledgerID, b.ProjectID
FROM (SELECT s.SubledgerID, sumid = SUM(coalesce(sp .ProductID, 0)),
cnt = COUNT(sp.Produc tID)
FROM SubledgerID s
LEFT JOIN SubledgerProduc t sp ON s.SubledgerID = sp.SubledgerID
GROUP BY s.SubledgerID) AS a
JOIN (SELECT p.ProjectID, sumid = SUM(coalesce(pp .ProductID, 0)),
cnt = COUNT(pp.Produc tID)
FROM Project p
LEFT JOIN ProjectProduct pp ON pp.ProjectID = p.ProjectID
GROUP BY p.ProjectID) AS b
ON a.sumid = b.sumid
AND a.cnt = b.cnt

It works that you get the same signature on ProductID no matter you
come from Subledger or you come from Project.

Now, the trouble here is finding a signature which does not give any false
positive. I know that there a similar problem, and I offered a suggestion
that Steve Kass proved not be safe. Unfortunately, I don't remember if
we ever found something that was waterproof. This time I didn't even
try, but I kind of hope that Steve who is a mathematician jumps in.

--
Erland Sommarskog, SQL Server MVP, so****@algonet. se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #6
Hi Simon,

This is my solution. I used your first example (because of its shorter
names!)
It's funny that we don't need table A at all. All we need is its
relations to B and C.
select
b,
c = (select C.c
from C left outer join AC on (C.c = AC.c and
a in (select a
from AB
where b = B.b)
)
group by C.c
having count(a) = (select count(*) from AB where b = B.b)
and count(a) = (select count(*) from AC where AC.c = C.c)
)
from B

Good Luck,
Shervin
si***@klickit.c om (Simon Withers) wrote in message news:<78******* *************** ****@posting.go ogle.com>...
I have 3 data tables, A, B and C, with many to many relationship
tables between A-B and A-C.

The data in A and C changes rarely, and the A-C relationship relates
all possible combinations of A to a C

If A contains A.1 to A.3 and C contains C.1 - C.8 then A-C could
contain the records:

A.1, C.1
A.2, C.2
A.3, C.3
A.1, C.4
A.2, C.4
A.1, C.5
A.3, C.5
A.2, C.6
A.3, C.6
A.1, C.7
A.2, C.7
A.3, C.7

so that any set of records from A (including the empty set) relates to
exactly on record in C

and suppose that B contains records from B.1 to B.3, and A-B contains
records
A.2, B.1
A.1, B.2
A.3, B.2

What I am having touble doing is crafting a query that will take me
from a record in B to the record in C that has the corrisponding set
of records in A-C as is in A-B for the chosen B.

ie, I want a query that will give me a result set something like

B.1, C.2
B.2, C.5
B.3, C.8

As far as I can come up with, this is not doable in a single query,
but perhaps I am missing something....

Simon Withers

Jul 20 '05 #7
Shervin Shapourian (Sh**********@h otmail.com) writes:
This is my solution. I used your first example (because of its shorter
names!)
It's funny that we don't need table A at all. All we need is its
relations to B and C.


Very nice solution! It spent some time to convince myself that it
addresses the general problem and not just produces the desired output
by chance, so to speak.

I did find a need for a minor improvement:

SELECT ProjectID, SubledgerID
FROM (SELECT ProjectID,
SubledgerID =
(SELECT C.SubledgerID
FROM SubledgerID C
LEFT JOIN SubledgerProduc t AC
ON C.SubledgerID = AC.SubledgerID
AND AC.ProductID IN (SELECT AB.ProductID
FROM ProjectProduct AB
WHERE AB.ProjectID = B.ProjectID)
GROUP BY C.SubledgerID
HAVING COUNT(AC.Produc tID) = (SELECT COUNT(*)
FROM ProjectProduct AB
WHERE AB.ProjectID = B.ProjectID)
AND COUNT(AC.Produc tID) = (SELECT COUNT(*)
FROM SubledgerProduc t AC
WHERE AC.SubledgerID =
C.SubledgerID)
)
FROM Project B) B
WHERE SubledgerID IS NOT NULL

As I understand the problem, it may be possible that there are projects
that does not map to subledgers and vice versa.
--
Erland Sommarskog, SQL Server MVP, so****@algonet. se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp
Jul 20 '05 #8
Hi Erland,

Thanks for the improvement and converting the script.

Good luck,
Shervin
"Erland Sommarskog" <so****@algonet .se> wrote in message
news:Xn******** *************@1 27.0.0.1...
Shervin Shapourian (Sh**********@h otmail.com) writes:
This is my solution. I used your first example (because of its shorter
names!)
It's funny that we don't need table A at all. All we need is its
relations to B and C.


Very nice solution! It spent some time to convince myself that it
addresses the general problem and not just produces the desired output
by chance, so to speak.

I did find a need for a minor improvement:

SELECT ProjectID, SubledgerID
FROM (SELECT ProjectID,
SubledgerID =
(SELECT C.SubledgerID
FROM SubledgerID C
LEFT JOIN SubledgerProduc t AC
ON C.SubledgerID = AC.SubledgerID
AND AC.ProductID IN (SELECT AB.ProductID
FROM ProjectProduct AB
WHERE AB.ProjectID = B.ProjectID)
GROUP BY C.SubledgerID
HAVING COUNT(AC.Produc tID) = (SELECT COUNT(*)
FROM ProjectProduct AB
WHERE AB.ProjectID = B.ProjectID)
AND COUNT(AC.Produc tID) = (SELECT COUNT(*)
FROM SubledgerProduc t AC
WHERE AC.SubledgerID =
C.SubledgerID)
)
FROM Project B) B
WHERE SubledgerID IS NOT NULL

As I understand the problem, it may be possible that there are projects
that does not map to subledgers and vice versa.
--
Erland Sommarskog, SQL Server MVP, so****@algonet. se

Books Online for SQL Server SP3 at
http://www.microsoft.com/sql/techinf...2000/books.asp

Jul 20 '05 #9
Wow,

Those are some well worked querys.

Thank you very much for them, they seem to address my situation.

In my specific probelem, there are no Projects that do not map to
Subledgers, but Subledger to Project does not alway match - the
Subeldger table will always map directly to all possible combinations of
Products, but not all possible combinations of Products will map to a
Project.

Simon Withers

*** Sent via Developersdex http://www.developersdex.com ***
Don't just participate in USENET...get rewarded for it!
Jul 20 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
2088
by: jason | last post by:
I could sure use some conceptualization and query help with a Page Watch System I am building in Access 2000 and Asp. I need to cycle through databae and generate a compiliation query email that notifies a person of yacht(s) that have changed on our website: Key database tables ---------------------------------------------------------------------------- Customer (1) --->> (many) Customer_Boats (many)<<---- Boat (1)
3
1932
by: Andrew Crowe | last post by:
Hi guys, I have a table currently set up like this: <- -> video ------ video_id
3
2927
by: jc3k | last post by:
I'm setting up a many-to-many relationship between an instructors table and a class table. 1 Instructor can have many classes. 1 Class can be held by more then one instructor. I'm using a bridging table between the 2. I placed a 3rd table between them that consists of (ID, Instructor_ID, Class_ID). The Instructor_ID and Class_ID were set to allow duplicates. These were then linked back to the Instructor and Class table.
1
2625
by: Phil W | last post by:
Hello, I have set up my database in access using many to many relationships (it's the good ol' books and authors one again). I've actually extended it to include other people who contribute in various ways to the books (e.g. editors, illustrators etc), so there's more than one many to many relationship there. When there's an entry in all the tables relating to the book I want to view, everything works fine (i.e. there's an author in...
4
2079
by: Apple | last post by:
I have to create a query with many to many relationship, but I can't break it into 2 x 1 to many, should there anyone can teach me how to solve this problem. Thanks in advance!
0
1406
by: CC | last post by:
Dear all, Following Many-to-Many table structure is part of my database ----------------------------------- TbGeneral (dossier information) PK: dsr_id TbDossierSample PK: dsr_sample_id
1
1036
by: pinkbear | last post by:
I have a many-to-many query that is giving me false positives. Let’s say I have some entities—Team Members and Teams. Team Members are onTeams, and they could be in one or many Teams. They are represented in tables thusly: Team Member: MemberID TeamMemberName Team: TeamID TeamName
14
2477
bugboy
by: bugboy | last post by:
I'm a beginner at this and am confused... I have three tables: 1. words / wordpk, word 2. definitions / definitionspk and definition 3. associations / wordpk, definitionspk 'words' holds words, 'definition' holds definitions for the words and 'associations' holds the pk associations between words and definitions because words can have many related definitions and definitions can many related words... many to many.
1
2702
by: smook | last post by:
Hi all I have a SQL Server 2000 database that I converted from an access database. The interface is still existing in Access... Basically I have 2 tables in a many to many relationship - Member and Nominators of members. But because the same nominator can nominate many members and a member can be nominated by multiple nominators, i've added a linking table call MemberNomLink that has the MemberId and the NominatorId. So in my...
0
9777
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10726
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10833
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10405
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7114
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5782
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4602
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4198
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3226
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.