mysqljoinmysql-error-1066

Mysql JOIN of four tables with two key tables


I hate to admit it by my knowledge of MySQL is lacking when it comes to the more complex queries. Essentially I have four tables two of them contain the data I want to return, and two are relational tables linking the data. Table A is present just to provide filler for Table D.aID.

+--------+ +--------+ +--------+ +-----------+ +-----------+
|Table A | |Table B | |Table C | |  Table D  | |  Table E  |
+---+----+ +---+----+ +---+----+ +---+---+---+ +---+---+---+
|aID|name| |bID|name| |cID|name| |dID|aID|bID| |eID|dID|cID|
+---+----+ +---+----+ +---+----+ +---+---+---+ +---+---+---+
| 1 | a_1| | 1 | b_1| | 1 | c_1| | 1 | 1 | 1 | | 1 | 1 | 1 |
+---+----+ | 2 | b_2| | 2 | c_2| | 2 | 1 | 2 | | 1 | 1 | 2 |
           +---+----+ | 3 | c_3| +---+---+---+ +---+---+---+
                      +---+----+

The relationship created with these tables is: Table A > Table B > Table C. The data I am wanting belongs to the Table B > Table C relationship.

+--------+---------+--------+---------+
|tblB.bID|tblB.name|tblC.cID|tblC.name|
+--------+---------+--------+---------+
|    1   |    a_1  |    1   |   c_1   |
|    1   |    a_1  |    2   |   c_2   |
|    2   |    a_2  |  NULL  |   NULL  |
+--------+---------+--------+---------+

However to ensure I am following the correct path I need to grab the Table B of the Table A > Table B relationship Table C belongs to. I realize that I am making things much more difficult for myself by allowing for duplicate name values, but I would rather have small tables and more complex queries than bloated tables and simpler queries. The query I am using is

SELECT * FROM `Table E`
LEFT JOIN `Table D` ON (`Table B`.bID = `Table D`.bID)
RIGHT JOIN `Table E` ON (`Table D`.dID = `Table E`.dID))
RIGHT JOIN `Table C` ON (`Table E.cID = `Table C`.cID);

However so far it has not worked. When the query is submitted this error is returned:

ERROR 1066 (42000): Not unique table/alias: 'Table D'

Any ideas on how I can get this to work? Is this even possible?


Solution

  • Thanks to Martin Smith I was able to come up with the solution I am posting here. I hope this might be able to help someone else.

    SELECT  tblB.bID,
        tblB.name,
        tblC.cID,
        tblC.name
    FROM Table E 
    RIGHT JOIN Table B ON (Table B.bID = Table D.bID)
    RIGHT JOIN Table D USING dID
    RIGHT JOIN Table C USING cID;