MySQL - Joining with an or statement?
I have a query where I want to join to another table if the field has either one value or another. How would I go about doing that? Should I use an or statement? (Is that even possible?) Or will an IN statement suffice?
SELECT table1.field1,table2.field2 FROM table1
INNER JOIN table2 ON table1.field1 = table2.field2 OR table2.field2 = 0
Basically the field in table 2 can either be a match from table 1 or the number 0, I want to make the match on either or. So if there is no match from table1 field and table2 field but there is a 0 in table2 field then I want to join the table. Hope that makes sense.开发者_JAVA技巧 Or would this work/be better?
SELECT table1.field1,table2.field2 FROM table1
INNER JOIN table2 ON table1.field1 IN(table2.field2,0)
I'd think about it slightly differently and start with table2
.
SELECT table1.field1, table2.field2
FROM table2
LEFT JOIN table1
ON table2.field2 = table1.field1
WHERE table2.field2 = 0
OR table1.field1 IS NOT NULL
精彩评论