SQL PHP:如果存在于另一个表中,则选择虚拟列
I'm making a notifications widget on my website and I'm trying to make it so that if a notification is marked as read, that notification ID will be inserted into another table (table 'b') along with their username so that it is marked as read. Now the problem that I run into is when displaying all notifications (whether they're read or unread) I don't know how to indicate if the notification exists in the secondary table
The currently SQL query is as follows:
$qry = "SELECT * FROM notifications WHERE (notif_recipient = '$user') ORDER BY notif_date DESC";
What I'd like to do is make the query much more complex in order to indicate if a notification exists in another table, so something along the lines of:
$qry = "SELECT notif_id,notif_message,(CASE SELECT notif_is_read AS '1' WHERE notif_id.notifications = notif_id.notifications_read ELSE SELECT notif_is_read AS '0') FROM notifications WHERE (notif_recipient = '$user') ORDER BY notif_date DESC";
Is something like this possible or is it as preposterous as my lack of ability for writing SQL queries
我正在我的网站上制作一个通知小部件,我正在努力使其成为通知,如果通知是 标记为已读,通知ID将与其用户名一起插入另一个表(表'b'),以便将其标记为已读。 现在我遇到的问题是显示所有通知(无论是已读还是未读)我不知道如何指示通知是否存在于辅助表中 p>
当前 SQL查询如下: p>
$ qry =“SELECT * FROM notifications WHERE(notif_recipient ='$ user')ORDER BY notif_date DESC”;
code>
我想要做的是使查询更加复杂,以指示另一个表中是否存在通知,所以类似于: p>
\ n
$ qry =“SELECT notif_id,notif_message,(CASE SELECT notif_is_read AS'1'WHERI notif_id.notifications = notif_id.notifications_read ELSE SELECT notif_is_read AS'0')FROM notifications WHERE(notif_recipient ='$ user' )ORDER BY notif_date DESC“;
code> pre>
这样的事情是可能的,还是因为我缺乏编写SQL查询的能力而荒谬 p>
As Marc B had suggested, I decided to use LEFT JOIN in order to identify which messages currently exist in the secondary table, with my query looking as such:
$qrytest = "SELECT notifications.notif_id,notifications.notif_message,notifications.notif_flag,notifications.notif_poster,notifications.notif_date,notifications_read.notif_read_count FROM notifications LEFT JOIN notifications_read ON notifications.notif_id=notifications_read.notif_id WHERE ((notif_recipient = 'all') OR (notif_recipient = '$id')) ORDER BY notif_date DESC,notif_flag DESC";
This in turn will return the results of my primary table (notifications) and if the same notification id exists in my secondary table, I decided to echo out that table's ID count, if the entry does not exist it will simply return as null
$exists = $row['notif_read_count'];
if ($exists !== ''){
// When NOT returning as null do something
} else {
// When exist returns as null do something
}