简体   繁体   中英

SQL Selecting rows from two tables where one column is common but another may be null

I am selecting from two tables, where table1 Person has the details of the persons, person_id, name etc and from table2 PersonSong (which is a one-to-many table for another table Song), which has person_id, song_id.

I have 5 persons, [1,2,3,4,5].

Each person can have multiple songs which are in PersonSong.

I need a query to show me to show me the list of the persons with the song_id that I search even if it is null.

Eg

               Person                               PersonSong
person_id       name        facebookId  |    person_id      song_id
                                        |
1               Bob         123         |            1          5
2               Bill        456         |            1          9
3               Jake        789         |            2          2
4               Mary        951         |            1          10
5               Kate        753         |            2          3
                                        |            3          5
                                        |            4          5
                                        |            5          8
                                        |            5          5

And if I search using person_id = 5 the answer should be,

Answer
person_id    person    facebookId    song_id
1            Bob       123           5
2            Bill      456           NULL
3            Jake      789           5
4            Mary      951           5
5            Kate      753           5

I want a list with all the persons and their data and an indication if they know the current song id.

You seem to just want a left join :

select p.*, ps.song_id
from person p left join
     personsong ps
     on p.person_id = ps.person_id and
        ps.song_id = 5;

You could try using a subquery which will allow you to get a full list of Person even if there are no joins into the table PersonSong

SELECT 
    p.person_id, p.name, p.facebookId,
    (SELECT 
            song_id
        FROM
            PersonSong ps
        WHERE
            ps.person_id = p.person_id
                AND ps.song_id = 5 LIMIT 1) as song_id
FROM
    Person p

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