Domanda

I've done a good bit of research on how to do this and was not able to find anything. I don't think what I'm trying to do is too difficult, but I'm not sure where to go from here and wanted to post this question.

I have two tables, one (DEVICE) is a table of devices and one (USER_DEVICE) is mapping a user to a device (user is assigned a device via this mapping table):

DEVICE        USER_DEVICE
id            user_id  device_id
------        -------  ----------
1             1        1
2             1        2
3             1        5
4             2        3
5
6

I'm trying to create an LEFT OUTER JOIN that will return all the devices from DEVICES currently NOT ASSIGNED to a specific user_id. For example, running this query for user_id 1 should return

DEVICE
id
------
3
4
6

And running this query for user_id 2 should return

DEVICE
id
------
1
2
4
5
6

I have created the following LEFT OUTER JOIN which successfully returns the following

SELECT id FROM DEVICE d LEFT OUTER JOIN USER_DEVICE ud ON d.id = ud.device_id WHERE ud.device_id IS null;

DEVICE
id
------
4
6

I'm not sure where I need to include the user_id=1 statement in the above sql. What I need is something to the effect of:

SELECT id FROM DEVICE d LEFT OUTER JOIN USER_DEVICE ud ON d.id = ud.device_id WHERE ud.user_id=1 AND ud.device_id IS null;

But this returns no rows. Any help on how to do this LEFT OUTER JOIN with a conditional statement looking for a specific user_id would be greatly appreciated! Thanks :)

È stato utile?

Soluzione

You want to include the condition on the device in the on clause:

SELECT id
FROM DEVICE d LEFT OUTER JOIN
     USER_DEVICE ud
     ON d.id = ud.device_id and
        ud.user_id = 1
WHERE ud.device_id IS null;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top