Frantisek
Frantisek

Reputation: 7693

MySQL LEFT JOIN only on some rows?

I have the following MySQL table:

enter image description here

On this table, I want to LEFT JOIN another table, but only to rows with action == 2 or action == 3. Is this possible with one SELECT by somehow specifying the LEFT JOIN part, or do I need to do more SELECTs and a UNISON?

EDIT: Rows with action = 1 can simply contain NULL values from the LEFT JOIN.

Upvotes: 0

Views: 475

Answers (2)

Nikola
Nikola

Reputation: 2132

SELECT * FROM table AS t LEFT JOIN another_table AS at ON t.id = at.id WHERE t.action = 2 OR t.action = 3

Doesn't this give you the result you are looking for?

Upvotes: 1

Marc B
Marc B

Reputation: 360612

SELECT ...
FROM sometable
LEFT JOIN jointable ON (sometable.field = jointable.field AND (action IN (2,3)))

you can have arbitrary logic in the JOIN conditions. All it has to do in the end is boil down to a true/false value. If the result is true, the join is successful and the joined fields are included. if the result is false, then the join does not occur for that particular row combination.

Upvotes: 4

Related Questions