Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
153 views
in Technique[技术] by (71.8m points)

sql - Problem with JOINs on selection of related data

I have three entity types (let's call them A, B, C) persisted on three tables of my database.

Each entity type has a relation with the other two entities. Relations are persisted in three tables of the DB as well (let's call them AB, AC, BC), where every record is a couple of IDs of the respective entities.

Relations A-B are one-to-many and are mandatory: every A has at least one relation with a B, every B has a relation with an A.

Relations A-C and B-C are many-to-many and are optional: there can be As without relation with Cs, there can be Bs without relations with Cs. I cannot change this schema.

I need to build a table with all the As and their related data. Every row of the table must contain only related data or NULLs where there are no relations. I thought I would be fine with something like:

SELECT * -- let's omit columns for simplicity
FROM      AB
LEFT JOIN BC ON BC.IdB = AB.IdB
LEFT JOIN AC ON AC.IdA = AB.IdA AND
                AC.IdC = BC.IdC
INNER JOIN A ON A.Id = AB.IdA
INNER JOIN B ON B.Id = AB.IdB
LEFT JOIN  C ON C.Id = AC.IdC

and then filtering with a WHERE clause. My problem is I don't get how, which makes me think I am approaching the problem in the wrong way.

Any hint would be appreciated, thank you in advance.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...