MariaDB: LEFT OUTER JOIN does not return row

允我心安 提交于 2020-01-06 18:00:21

问题


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 all NULLs.
  • 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!