Skip to content
Advertisement

create column for unread notifications in union query

I’m trying to distinguish two unioned selects. I have two tables: notification and read_notification.

notification table:

id   title   body
-----------------

read_notification table:

id  user_id  notification_id
----------------------------

I’ve managed with getting unread and read notifications like so:

SELECT id, 
       title_ru 
FROM   notification 
WHERE  id NOT IN (SELECT notification_id 
                  FROM   read_notification 
                  WHERE  user_id = 1) 
UNION 
SELECT id, 
       title_ru 
FROM   notification 
WHERE  id IN (SELECT notification_id 
              FROM   read_notification 
              WHERE  user_id = 1) 

and got result where unread notifications come first then read:

id   title
----------
2   title2
3   title3
4   title4
1   title1

Now I need to distinguish them, so I need a read column where unread notifications will be marked with 1. Should look like this:

id   title   read
-----------------
2    title2   1
3    title3   1
4    title4   1
1    title1   0

Can’t get the idea of how to form it.

Advertisement

Answer

Add it as a literal in the SELECT list.

SELECT id, 
       title_ru,
       0 AS isread
FROM   notification 
WHERE  id NOT IN (SELECT notification_id 
                  FROM   read_notification 
                  WHERE  user_id = 1) 
UNION 
SELECT id, 
       title_ru,
       1 AS isread
FROM   notification 
WHERE  id IN (SELECT notification_id 
              FROM   read_notification 
              WHERE  user_id = 1) 

You can also do this without UNION by using LEFT JOIN.

SELECT id, title_ru, IF(r.notification_id IS NULL, 0, 1) AS isread
FROM notification AS n
LEFT JOIN read_notification AS r ON n.id = r.notification_id AND r.user_id = 1

or with a correlated subquery

SELECT id, 
        title_ru, 
        EXISTS (
            SELECT 1 FROM read_notifications as r
            WHERE r.notification_id = n.id
            AND r.user_id = 1) AS isread
FROM notification AS n
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement