简体   繁体   English

SQL PHP:如果另一个表中存在虚拟列,请选择

[英]SQL PHP: Select virtual column if exists in another table

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. 我正在网站上制作一个通知窗口小部件,并试图将其放置为如果通知被标记为已读,则该通知ID将与用户名一起插入另一个表(表'b')中,以便标记为已读。 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: 当前的SQL查询如下:

$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 像这样可能吗?或者像我缺乏编写SQL查询功能的能力一样荒唐

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: 正如Marc B所建议的那样,我决定使用LEFT JOIN来确定辅助表中当前存在哪些消息,查询如下所示:

$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 反过来这将返回主表(通知)的结果,如果辅助表中存在相同的通知ID,我决定回显该表的ID计数,如果该条目不存在,它将简单地返回为null

    $exists = $row['notif_read_count'];
if ($exists !== ''){
  // When NOT returning as null do something
 } else {
  // When exist returns as null do something
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM