Mysql JOIN of four tables with two key tables

风格不统一 提交于 2019-12-12 14:03:48

问题


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?


回答1:


The query you say you are submitting bears little resemblance to the table structure you have given us! What is Table D.national_regionID? Or modx.coverage_state?

Generally though don't mix left and right joins. Also every table used in the query must either follow the FROM or follow a JOIN. You seem to be using Table B and Table C in join conditions without ever adding them to the query.




回答2:


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;


来源:https://stackoverflow.com/questions/3824389/mysql-join-of-four-tables-with-two-key-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!