简体   繁体   中英

LEFT JOIN or INNER JOIN?

I have the following tables. All fields are NOT NULL .

tb_post
    id
    account_id
    created_at
    content

tb_account
    id
    name

I want to select the latest post along with the name. Should I use INNER JOIN or LEFT JOIN ? From my understanding both produce the same results. But which is more correct or faster?

SELECT p.content, a.name
FROM tb_post AS p
[INNER or LEFT] JOIN tb_account AS a
ON a.id = p.account_id
ORDER BY p.created_at DESC
LIMIT 50

A LEFT JOIN is absolutely not faster than an INNER JOIN. In fact, it's slower; by definition, an outer join (LEFT JOIN or RIGHT JOIN) has to do all the work of an INNER JOIN plus the extra work of null-extending the results. It would also be expected to return more rows, further increasing the total execution time simply due to the larger size of the result set.

(And even if a LEFT JOIN were faster in specific situations due to some difficult-to-imagine confluence of factors, it is not functionally equivalent to an INNER JOIN, so you cannot simply go replacing all instances of one with the other!)

Better go for INNER JOIN.

As Per My View The Correct One Is Inner join

because it returns resultset that include only matched elements where Left Join Returns all entries from Left Table. In this case I think Inner join returns the only required amount of data to be proceed.

You have to ask yourself two questions.

1) Is there any chance that at some point in your application lifetime, there will be posts with an empty or invalid account_id ?

If not, it doesn't matter.

If yes...

2) Would it be desirable to include posts without an associated account in the result of the query? If yes, use LEFT JOIN, if no, use INNER JOIN.

I personally don't think speed is very relevant: the difference between them is what they do.

They happen to give the same result in your case, but that does not mean they can be interchanged, because choosing the one or the other still tells the other guy that reads your code something.

I tend to think like this: INNER JOIN - the two tables are basically ONE set, we just need to combine two sources. LEFT JOIN - the left tables is the source, and optionally we may have additional information (in the right table).

So if I would read your code and see a LEFT JOIN, that's the impression you give me about your data model.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM