问题
I already tried various types of JOINS but I am not able to get this simple query to work. I would like to have the result of table a in any case, even if there is no corresponding entry in table b. I tried:
SELECT a.user_id,
a.user_name,
b.first_name
FROM users a
LEFT OUTER JOIN members b
ON a.member_uid = b.uid
WHERE (a.user_name = 'TEST'
AND b.active = 1)
In this case, there is no entry in b that has b.active = 1. But I assumed that all wanted columns from a would be returned and the column from b would be null. But when running this query in the SQL window of the MariaDB, zero rows are returned.
Any help would be highly appreciated!!
回答1:
Left Outer Join will get all the rows/data from table a whether they are matching or not-matching in table b. But you are again filtering out the data by putting conditions in where clause. Since, there is no entry in b that has b.active = 1 so there will be no output. Remove b.active = 1 from the query, like this :
SELECT a.user_id,
a.user_name,
b.first_name
FROM users a
LEFT OUTER JOIN members b
ON a.member_uid = b.uid
WHERE a.user_name = 'TEST';
回答2:
It matters whether you put things in ON
or WHERE
when doing LEFT JOIN
. ("OUTER" is ignored.)
SELECT a.user_id,
a.user_name,
b.first_name
FROM users a
LEFT OUTER JOIN members b
ON a.member_uid = b.uid
AND b.active = 1 -- Note
WHERE a.user_name = 'TEST'
Think of it this way:
- If
ON
is false, keep the row, but with allNULLs
. - If
WHERE
is false, don't return the row.
回答3:
I found a way to make it work with mariaDB, you make subqueries from both tables and then join. Not the best but it works:
SELECT a.user_id,
a.user_name,
b.first_name
FROM (select * from users WHERE user_name = 'TEST') a
LEFT JOIN (SELECT * from members WHERE active = 1) b
ON a.member_uid = b.uid
If anyone knows the proper way to do this, please comment.
来源:https://stackoverflow.com/questions/43716641/mariadb-left-outer-join-does-not-return-row