简体   繁体   中英

Sql query to get Expected output

I have three tables named device_table, playlist_table and device_playlist_assoc

The device_playlist_assoc table is used to associate the device with the playlist.

device_table

device_id device_name
d1 device1
d2 device2
d3 device3
d4 device4
d5 device5
d6 device6

playlist_table

playlist_id playlist_name
p1 playlist1
p2 playlist2
p3 playlist3

device_playlist_assoc

dpa_id dpa_device_id dpa_playlist_id
1 d1 p1
2 d1 p2
3 d2 p1
4 d2 p3
5 d3 p4
6 d4 p5

So, O/PI want is to have those devices that don't have the playlist1 . I only get playlist_id from the frontend as a parameter. So i want an sql query that can give me expected output based on this playlist_id only. ie whatever playlist_id i get from frontend, i should be able to get the device_id of devices that dont contain that playlist + those devices also that doesnot contain any playlist.

Expected O/P

device_id
d3
d4
d5
d6

I tried with left outer join but i was not getting expected o/p. Can someone please help? Thanks.

here is how you can do it:

select * 
from device_table
where device_id not in (select device_id 
                        from device_playlist_assoc
                        where playlist_id = 1)

I would recommend not exists :

select d.*
from device_table d
where not exists (select 1
                  from device_playlist_assoc dp
                  where dp.dpa_device_id = d.device_id and
                        dp.dpa_playlist_id = ?
                 );

The ? is a parameter placeholder for the id passed in from the application code.

I prefer not exists over not in for two reasons:

  1. It behaves as you would expect if the subquery returns NULL values.
  2. It is easy to optimize using indexes (in this case on device_playlist_assoc(dpa_device_id, dpa_playlist_id) .

I would speculate, though, that you might want to refer to the playlist by name and not by id. If that is the case, you can use a join in the subquery:

select d.*
from device_table d
where not exists (select 1
                  from device_playlist_assoc dp join
                       playlist_table p
                       on dp.dpa_playlist_id = p.playlist_id
                  where dp.dpa_device_id = d.device_id and
                        p.playlist_name  = ?
                 );

In this case, the ? is a parameter placeholder for the name, rather than the id .

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