我正在制作一个简单的通知系统,但无法使查询正常工作,我感到困惑。
我想从表1中选择所有“看不见”的通知,考虑到表2中没有匹配结果时看不见。
table1 t1 (notifications)
+---+-------+--------+
+id + title + content+
+---+-------+--------+
+ 1 + some..+lorem...+
+ 2 + sosf + sfdsdf +
+ 3 + asdf + dsfd +
+---+-------+--------+
table2 t2 (seen notification by each user)
+-------+---------------+
+id_user+id_notification+
+-------+---------------+
+ 1 + 1 +
+ 1 + 3 +
+-------+---------------+
因此,当t2上没有匹配的记录时,我想查询t1的所有记录。
我试过了
SELECT t1.*
FROM t1
JOIN t2 ON t2.id_user IS NULL AND t1.id IS NULL
ORDER BY t1.id DESC;
没有运气
您需要使用LEFT JOIN
来联接上的表notification_id
。哪里有中没有匹配值t2
,值t2.notification_id
将是NULL
:
SELECT t1.*
FROM t1
LEFT JOIN t2 ON t2.id_notification = t1.id
WHERE t2.id_notification IS NULL
输出:
id title content
2 sosf sfdsdf
要查看特定用户是否已查看通知,请将ON
条件更改为以下内容:
LEFT JOIN t2 ON t2.id_notification = t1.id AND t2.id_user = 2
这将为您提供用户2未看到的所有通知,在这种情况下,它们都是:
id title content
1 some.. lorem...
2 sosf sfdsdf
3 asdf dsfd
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句