[英]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.