I’m a little stuck with an sql query. I’ve searched everywhere but to no avail so was hoping somebody here could help.
I have 2 tables.
Table 1 is a list of notifications with the following columns
notification_id(this is the auto incremented primary key)notification(This is the notification message)from_id(This is the user_id of the person sending the notification)
eg.
| notification_id | notification | from_id |
| 25 | this message | 7 |
| 26 | that message | 8 |
Table 2 shows which users have read each notification. It has the following columns
notification_id(this is the id of the relevant notification)user_id(This is the user id of the person who has read the notification)
eg.
| notification_id | user_id |
| 25 | 1 |
| 25 | 2 |
| 25 | 3 |
| 26 | 2 |
The tables are joined on notification_id and we have a one to many relationship as many users will read each notification.
What I am trying to do is query the database to return all the notifications that the particular user has not already read. In other words I want the data from table one but only if table 2 doesn’t have an entry where user_id is (My user_id x) for the corresponding notification_id.
So if my user_id is 4 then I get the data for both notification_id 25 and 26 as user_id 4 is not listed in table 2 for either of those
If my user_id is 2 I don’t get any data as user_id 2 is listed in table 2 as having read both notification_id 25 and 26
If my user_id is 1 I get the data for notification_id 26 but not 25
I originally thought I could use this
SELECT
notification_id, notification, from_id
FROM table_1
INNER JOIN table 2
ON table_1.notification_id = table2.notification_id
WHERE table2.user_id != X
But this is actually a long way off what I need and I’ve reached a bit of a dead end.
Thanks
I would do a left join and look for empty joins.