Question

I am a newbie for SQL database and i am playing with some tables to get the columns by using JOIN like that.

I have a Table like the following

A - id, A1
B - id, B1, B2, B3
C - id, C1, C2, c3


AB - id, A_id, B_id 

AC - id, A_id, C_id

Now, I want to do some joins and I would like to get the results like,

B1, B2, B3, C1, C2, C3

Even though, I seen some of the same type question and i could not understand. So, if the answer be simply explained in detail would be very grateful. Thanks

Was it helpful?

Solution

SELECT B1, B2, B3, C1, C2, C3
FROM A
INNER JOIN AB ON A.id = AB.A_id
INNER JOIN B ON B.id = AB.B_id
INNER JOIN AC ON A.id=AC.A_id
INNER JOIN C ON C.id = AC.C_ID

EDIT:

If the columns in the tables have the same names (e.g. there is a colum B.column1 and a column C.column1) do:

SELECT B.column1, B.B1, B.B2, B.B3, C.column1, C.C1, C.C2, C.C3
FROM A
INNER JOIN AB ON A.id = AB.A_id
INNER JOIN B ON B.id = AB.B_id
INNER JOIN AC ON A.id=AC.A_id
INNER JOIN C ON C.id = AC.C_ID

EDIT 2: For long table names you can do:

SELECT b.B1, b.B2, b.B3, c.C1, c.C2, c.C3
FROM A_LONG_NAME a
INNER JOIN AB ON a.id = AB.A_id
INNER JOIN B_LONG_NAME b ON b.id = AB.B_id
INNER JOIN AC ON a.id=AC.A_id
INNER JOIN C_LONG_TABLE_NAME c ON c.id = AC.C_ID
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top