[英]How to query a table not to include data if id exists on the related table?
Here's my tables. 这是我的桌子。
Notification Table 通知表
+----+--------------+
| Id | Subject |
+----+--------------+
| 1 | Loreum Ipsum |
| 2 | Hello World |
| 3 | Pls Help |
+----+--------------+
UserNotification Table 用户通知表
+----+----------------+--------+
| Id | NotificationId | Status |
+----+----------------+--------+
| 1 | 1 | Read |
+----+----------------+--------+
I want to query notification table without including data if NotificationId
exists on the UserNotification
Table 如果UserNotification
表上存在NotificationId
我想查询通知表而不包含数据
I want result: 我想要结果:
Notification Table 通知表
+----+-------------+
| Id | Subject |
+----+-------------+
| 2 | Hello World |
| 3 | Pls Help |
+----+-------------+
Use NOT EXISTS
使用NOT EXISTS
Query 询问
SELECT * FROM Notification n
WHERE NOT EXISTS(
SELECT 1 FROM UserNotification u
WHERE n.Id = u.NotificationId
);
sql fiddle demo
You can use not in 你可以不用
select Id,Subject from notificationTable where Id not in (select Id from userNotificationTable) ;
You also can use JOIN
: 您还可以使用JOIN
:
SELECT n.*
FROM Notification n
JOIN UserNotification un
ON n.Id <> un.NotificationId
You can achieve this by LEFT JOIN
with NULL
check: 您可以使用NULL
检查通过LEFT JOIN
实现:
SELECT N.Id, N.Subject
FROM `Notification` N
LEFT JOIN `UserNotification` U ON U.NotificationId = N.Id
WHERE U.NotificationId IS NULL
Use NOT IN 使用NOT IN
Select * from Notification where id NOT IN (SELECT id FROM UserNotification)
This sql will help for get data 这个SQL将有助于获取数据
SELECT n.Id, n.Subject FROM Notification n
LEFT JOIN UserNotification nu on nu.NotificationId = n.id
WHERE nu.id IS NULL
you want to return the notification that are no in usernotification 您想要返回用户通知中没有的通知
try this : 尝试这个 :
select Id,Subject
from Notification
where
id not in (
select distinct NotificationId from UserNotification
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.