I have three tables AA, BB and CC. BB and CC has one to one mapping to table AA ( with foreign key column : aa_id in both tables). Provided one condition that only either BB or CC can have reference to a row of table AA.
I would like to select latest 1000 rows from AA either joining with BB or CC.
I could do separate queries to select 500 rows joining with BB and CC separately and make 1000. But this will not guarantee that I am getting latest 1000 rows from AA table.
So, I came up with following query to select record from AA by joining with BB and CC at same time. But due to my restriction ( only either BB or CC can have reference to a row of table AA), I am getting 0 rows from query below.
SELECT * FROM AA
INNER JOIN BB ON (
AA.id = BB.aa_id
AND SOME_CONDITION
)
INNER JOIN CC ON (
AA.id = CC.aa_id
AND SOME_CONDITION
)
ORDER BY
AA.id DESC limit 1000;
Could you please tell me how to do this? Is there any way so that I can OR these two JOIN conditions?
just change your
INNER JOINs toLEFT OUTER JOINs and you’ll be fine. you may want to read this article on codinghorror.com for an explanation of different join-types.your result should look like this: