簡體   English   中英

如果相關表上存在id,如何查詢不包含數據的表?

[英]How to query a table not to include data if id exists on the related table?

這是我的桌子。

通知表

+----+--------------+
| Id | Subject      |
+----+--------------+
| 1  | Loreum Ipsum |
| 2  | Hello World  |
| 3  | Pls Help     |
+----+--------------+

用戶通知表

+----+----------------+--------+
| Id | NotificationId | Status |
+----+----------------+--------+
| 1  | 1              | Read   |
+----+----------------+--------+

如果UserNotification表上存在NotificationId我想查詢通知表而不包含數據

我想要結果:

通知表

+----+-------------+
| Id | Subject     |
+----+-------------+
| 2  | Hello World |
| 3  | Pls Help    |
+----+-------------+

使用NOT EXISTS

詢問

SELECT * FROM Notification n
WHERE NOT EXISTS(
    SELECT 1 FROM UserNotification u
    WHERE n.Id = u.NotificationId
);

sql fiddle demo

你可以不用

select Id,Subject from notificationTable
where Id not in (select Id from userNotificationTable) ;

您還可以使用JOIN

SELECT n.*
FROM Notification n
JOIN UserNotification un
ON n.Id <> un.NotificationId

SQLFiddle演示

你可以做..

Select * from Notification
left join UserNotification on Notification.id = UserNotification.NotificationId
where UserNotification.id is null

SQLFiddle

您可以使用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

使用NOT IN

Select * from Notification where id NOT IN (SELECT id FROM UserNotification)

這個SQL將有助於獲取數據

SELECT n.Id, n.Subject FROM Notification n
LEFT JOIN UserNotification nu on nu.NotificationId = n.id
WHERE nu.id IS NULL

您想要返回用戶通知中沒有的通知

嘗試這個 :

select Id,Subject
from Notification  
where 
id not in (
select distinct NotificationId  from UserNotification
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM