mysqlsqlright-join

Why this RIGHT join returns invoices with state other then pending?


I'm building library which generates SQL queries and found case which i don't understand why it is happening so. I agree that in general you should filter out by "where" and not "on" yet ON allows to filter out for LEFT join. Though for RIGHT join i get results that do not match ON request. I wonder why RIGHT join works this way.

Users (table name _user):

enter image description here

Invoices (table name _invoice):

enter image description here

Query:


 SELECT
    _user.id AS userId,
    _user.name AS userName,
    _user.state AS userState,
    _invoice.id AS invoiceId,
    _invoice.userId AS invoiceUserId,
    _invoice. `state` AS invoiceState
FROM
    _user
    RIGHT JOIN _invoice  on _invoice.state = 'pending'

Response:

enter image description here

Question:

Would be best to get step-by-step execution for this query-result to understand how exactly it happen.


Solution

  • A right join keeps all rows from the second table regardless of whether the on clause evaluates to "true", "false", or NULL.

    Presumably, though, you want a valid join condition. My guess is you want a list of all users and any pending invoices. If so, the correct logic would be:

    SELECT . . .
    FROM _user u LEFT JOIN
         _invoice i
         ON i.userid = u.id AND i.state = 'pending';
    

    At the very least, this produces a result that seems usable.