Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct Join Query for SQL Query

I currently have the following Query

SELECT * FROM tbl_Cars c
        INNER JOIN tbl_Car_Parts cp ON c.Id = cp.Id
        INNER JOIN tbl_Car_Factory cf ON cp.Id = cf.Id

However I have now realised that there are some Ids which are in the Cars Table which are then not in the Car Parts table so these are being omitted from my results while I want them included. I tried changing my INNER JOIN to a LEFT OUTER JOIN but it made no difference in the result set I am returned?

like image 903
Ctrl_Alt_Defeat Avatar asked Dec 28 '25 16:12

Ctrl_Alt_Defeat


1 Answers

Use LEFT OUTER JOIN in both of the joins.

SELECT * FROM tbl_Cars c
    LEFT OUTER JOIN tbl_Car_Parts cp ON c.Id = cp.Id
    LEFT OUTER JOIN tbl_Car_Factory cf ON cp.Id = cf.Id

Otherwise the second INNER JOIN will invalidate your first LEFT OUTER JOIN for those records that does not have ID (does not join) in the tbl_Car_Parts table.

After a LEFT OUTER JOIN you may be only use again INNER JOIN if the table you are joining is not related with the previous ones that are joined using the LEFT OUTER JOIN.

like image 197
Rafa Paez Avatar answered Dec 31 '25 09:12

Rafa Paez