我有 2 張表,一張是“用戶訪問”,一張是“通知資訊”。我想根據 tblUserNotify 中此用戶的條件,為 tblUserVisit 中的特定用戶選擇用戶訪問。
如果我只從 tblUserVisit 中選擇資料,我會得到 2 條記錄:
SELECT TOP (1000) [Id]
,[SiteId]
,[UserName]
,[Visited]
,[Created]
,[Status]
FROM [tblUserVisit]
where visited = 'lilje' and siteid='3' and status = '0'

到現在為止還挺好。現在我想檢查 tblUserVisit 結果中的用戶在 tblUserNotify 中是否具有 Notification Type = 7。只回傳通知型別 = 7 的用戶。
這樣做時,我會得到多條記錄。tblUserNotify.Value = nothing 的記錄是正確的(第一條和第三條記錄)。我還得到了 tblUserNotify.Value = 0 的 2 條記錄。這是我的代碼:
SELECT tblUserVisit.Id, tblUserVisit.SiteId, tblUserVisit.UserName, tblUserVisit.Visited, tblUserVisit.Created, tblUserVisit.Status, tblUserNotify.Type, tblUserNotify.Value
FROM tblUserVisit INNER JOIN
tblUserNotify ON tblUserVisit.Visited = tblUserNotify.UserName
WHERE (tblUserVisit.Status = '0') AND (tblUserVisit.SiteId = '3') AND (tblUserNotify.Type = '7') AND (tblUserVisit.Visited = 'lilje')
ORDER BY tblUserVisit.Id

我也嘗試過使用 LEFT JOIN,但沒有解決問題。
這是 tblUserNotify 的樣子:

希望有人可以幫我修改SQL,這樣在加入tblUserNotify 表時它不會從tblUserVisits 回傳兩次記錄。
uj5u.com熱心網友回復:
我會添加一個EXISTS條款:
SELECT TOP 1000 [Id]
,[SiteId]
,[UserName]
,[Visited]
,[Created]
,[Status]
FROM [tblUserVisit] tuv
WHERE visited = 'lilje' AND siteid = '3' AND status = '0' AND
EXISTS (SELECT 1 FROM [tblUserNotify] tun
WHERE tun.UserName = tuv.Visited AND [Type] = '7');
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/366501.html
標籤:sql
下一篇:Sql多重嵌套選擇
