[英]Select distinct values from db
我有兩張桌子
用戶:
id,
username
和
應用:
userid,
appid,
mainid
我想顯示在此表中沒有記錄的用戶。我從地址mainId
和appid
。如果我運行此查詢
SelectQuery("select User.UserName
from User
INNER JOIN App
ON User.Id = App.UserId
where App.Mainid!= ".$var_MainId." and App.AppId<>".$var_AppId);
它不顯示,可能有相同的用戶userid
和mainid
但不相同appid
您可以使用一個not exists
子句。 例如,要查找沒有使用MainId 123和AppId 456的應用程序條目的用戶:
select u.UserName
from User u
where not exists
(
select *
from App a
where a.UserId = u.Id
and a.MainId = 123
and a.AppId = 456
)
我建議使用反連接模式。 但是規范不是很清楚。 (樣本數據和預期輸出將對澄清它們大有幫助。)
SELECT u.id
, u.username
FROM user u
LEFT
JOIN app a
ON a.userid = u.id
AND a.mainid <=> ?
AND a.appid <=> ?
WHERE a.userid IS NULL
這個查詢將返回來自行u
那里沒有匹配的行中a
具有用於mainid和的appid指定的值。
給定user
表的內容為
id username
---- --------
2 foo
3 fee
5 fi
和app
表為
userid appid mainid
------ ----- ------
2 444 888
3 444 1
3 1 888
如果我們在查詢中為appid
指定444的值,為mainid
指定888的值,例如
SELECT u.id
, u.username
FROM user u
LEFT
JOIN app a
ON a.userid = u.id
AND a.mainid <=> 444
AND a.appid <=> 888
WHERE a.userid IS NULL
該查詢將返回用戶3和5。(不會返回用戶2,因為app
存在與規范匹配的一行。)
還有其他查詢模式將返回等效結果。 使用NOT EXISTS (correlated subquery)
模式可能是最容易理解的模式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.