简体   繁体   中英

get null values with Where and left join

Let's have this query

   select music,fav from MUSIC music

        left join  Favorite_Music fav on fav.id_music  = music.id_music  

        where fav.id_user= 22 or fav.id_user is NULL

my Table Music :

  id_music  |  ....

     1      |  
     ...    |   
     100    |  

my Table Favorite_Music :

id_fav  |  id_music  |  id_user

 1      |   15        |  22  
 2      |   20        |  22  
 3      |   40        |  30  

I want to retrieve all MUSIC and for some stuff i want to mark the favorite musics of my user 22 .

But when i execute the query above the music 40 is not included !!

So i want to get all the music and get null value for Favorite_Music which are not of my 22 user.

You have to apply filters to outer joined tables in the join clause, not the where clause. Like this:

select music,fav 
from MUSIC music
left join  Favorite_Music fav on fav.id_music  = music.id_music  
and (fav.id_user= 22 or fav.id_user is NULL )

When you filter in the where clause, which seems like an obvious thing to do, your outer join becomes an implicit inner join.

This is the query that I think you want:

select music, (case when fav.id_user is not null then 'No' else 'Yes' end) as IsFav22
from MUSIC music left join
     Favorite_Music fav
     on fav.id_music = music.id_music and fav.id_user = 22;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM