Search code examples
mysqlsqljoinrelationshipsql-like

SQL Join tables that have both a one to one and one to many relationship


The title is probably a bad title but I cannot think of a better one...

I have a kind of unique schema, where that I have 5 tables with relationships, but one of the tables has a relationship with two tables. To make it less confusing, let me show you the schema:

Table A:

AID BID Name
1   1   101
2   1   102
3   1   103
4   2   104
5   3   105
6   4   106

Where AID is the Primary ID to table A and BID is a primary ID to table B

Table B:

BID   CID   DID   Name
1     null  3     101
2     null  4     102
3     1     null  103
4     2     null  104

where either CID is null or DID is null

Table C:

CID   DID   Name
1     1     A
2     2     B
3     3     A
4     4     B
5     5     C
6     5     A

Table D:

DID   EID   Name
1     1     Alpha
2     1     Bravo
3     1     Charlie
4     1     Echo
5     2     Delta

Table E:

EID   Name
1     Home
2     Away

I know this may be a bit confusing but basically the data can do one of two things:

  1. The data in table A can connect to B, then C, then D then E, or
  2. The data in table A can connect to B, then D, then E

My issue is that I want to create a SQL query that will Join all of the tables, grabbing A.Name, A.AID, and E.Name from any row where B.Name LIKE '%Some name%', C.Name LIKE '%Some name%', D.Name LIKE '%Some name%', and E.Name LIKE '%Some name%'.

so for example, I want a query that if I set E.Name LIKE '%Home%', the query will return:

E.Name    E.EID    D.DID    C.CID    B.BID    A.AID    A.Name
Home      1        3        null     1        1        101
Home      1        3        null     1        2        102
Home      1        3        null     1        3        103
Home      1        4        null     2        4        103
Home      1        1        1        3        5        103
Home      1        2        2        4        6        103

Currently my current query only returns "random" data, and by that I mean it returns something but not the right thing and I can't figure out what the rows it is returning have in common that the query is pulling. But basically my query is:

select ... from tableA, 
inner join tableB on A.BID=B.BID 
inner join tableC on B.CID=C.CID 
inner join tableD on C.DID=D.DID OR B.DID=D.DID 
inner join E.EID = D.EID
WHERE E.Name LIKE '%Home%';

Any suggestions would be great! Thank you!!!


Solution

  • If you change a couple of your INNER JOINs to LEFT JOINs you should get your desired results.

    SELECT e.Name, e.EID, d.DID, c.CID, b.BID, a.AID, a.Name
    FROM TableA a
    INNER JOIN TableB b ON a.BID = b.BID
    LEFT JOIN TableC c ON b.CID = c.CID
    INNER JOIN TableD d ON c.DID = d.DID or b.DID = d.DID
    INNER JOIN TableE e ON d.EID = e.EID
    WHERE e.Name LIKE '%Home%'