How to make a multi-join query in MySQL?
I'm new to SQL, and find I don't quite understand which joins to use when. Sub-queries also seem confusing. I have the following tables set up, and I'm trying to get a specific outcome:
`+--------------------------+ +---------------+ +---------------+ +---------------+`
`| Table_A | | Table_B | | Table_C | | Table_D |`
`+--------------------------+ +---------------+ +------------开发者_StackOverflow中文版---+ +---------------+`
`| id | f2 | f3 | f4 | d_id | | a_id | c_id | | id | fc | | id | fs |`
`+--------------------------+ +---------------+ +---------------+ +---------------+`
And this is what I'm trying to get:
`+----------------------------------+`
`| a.f2 | a.f3 | a.f4 | d.fs | c.fc |`
`+----------------------------------+`
I've found that I can get the first four columns with the following query:
Select t1.f2, t1.f3, t1.f4, t2.fs
From Table_A AS t1 INNER JOIN Table_D AS t2
ON t1.d_id = t2.id;
How can I get from A.id to C.fc? I can't figure out how to get the fifth column, let alone in conjunction with the previous query. This is about as far as I got with the final column:
Select t1.flow_control
FROM Table_D AS t1 INNER JOIN policy t2
ON t1.id = t2.c_id;
This should do the trick:
Select t1.f2, t1.f3, t1.f4, t2.fs, t3.fc
From Table_A AS t1
INNER JOIN Table_D AS t2 ON t1.d_id = t2.id
INNER JOIN Table_B AS jointable ON t1.id = jointable.a_id
INNER JOIN Table_C AS t3 ON jointable.c_id = t3.id;
The first join is the one you originally had. The second one is for the 'linking table', which represents a HABTM relationship between Table_A and Table_C. Once you've joined with that, you do a third join 'connecting' it to Table C so you can get that 'fc' field. So essentially the first join is just for Table_D, and the two other JOINs get you to that last field.
You can have multiple JOINs in a single statement that link to completely different tables if that's what you need... it's just like connecting the dots / following the relationships :)
精彩评论