I’d like a query that shows me the tracks that a user doesn’t have in his playlist. The only parameter I’ll be getting is the username of a user.
Is that possible with this diagram? If so, could you provide me with a query?
I’ve tried a query, but not so succesfull.
SELECT * FROM TRACK INNER JOIN USER u on u.ID = TRACK.USERID INNER JOIN Playlist p on p.TrackID = TRACK.ID WHERE (u.ID IN (SELECT UserID FROM Playlist WHERE UserID = (SELECT ID FROM User WHERE username = 'Arjan'))) AND (TRACK.ID NOT IN (SELECT ID FROM TRACK))
Not sure what’s missing here. Maybe I’m just thinking too complicated.
Advertisement
Answer
I didn’t get a chance to try it out actually. But your query should be something like this one —
Declare @UserName varchar(255) Set @UserName = N'Arjun' SELECT U.ID ,U.UserName ,P.ID ,T.Id ,T.TrackUrl ,T.CreationDate FROM TRACK T INNER JOIN USER U ON U.ID = T.UserID LEFT JOIN Playlist P ON P.TrackID = T.ID AND P.UserID = U.ID WHERE U.ID IN ( SELECT DISTINCT ID FROM User WHERE UserName = @UserName ) AND P.ID IS NULL;