Php 从数据库中选择不同的值
我有两张桌子 用户:Php 从数据库中选择不同的值,php,mysql,sql,localhost,Php,Mysql,Sql,Localhost,我有两张桌子 用户: id, username 及 应用程序: 我想显示此表中没有记录的用户。我从地址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); SelectQuery(“选择Us
id,
username
及
应用程序:
我想显示此表中没有记录的用户。我从地址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);
SelectQuery(“选择User.UserName
来自用户
内部加入应用程序
ON User.Id=App.UserId
其中App.Mainid!=“$var\u Mainid.”和App.AppId“$var\u AppId”);
它不显示可能具有相同
userid
和mainid
但不相同appid
的用户。您可以使用不存在
子句。例如,要查找没有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
)
我建议使用反连接模式。但是规格不是很清楚。(样本数据和预期输出将大大有助于澄清这一点。) 和
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
选择u.id
,u.username
来自用户u
左边
加入应用程序a
在a.userid=u.id上
和a.mainid 444
和a.appid 888
其中a.userid为NULL
此查询将返回用户3和5。(不会返回用户2,因为app
中有一行与规范匹配。)
还有其他查询模式将返回相同的结果。使用
不存在(相关子查询)
模式可能是最容易理解的模式。如果我执行以下查询where App.Mainid=“.var_Mainid.”和App.AppId=“.var_AppId”);
它只显示一个用户(正确)我在数据库中有两个用户,即使你的解决方案有效,但我只能接受一个,我不能给你+1,因为我的分数低于15,但谢谢anyway@RandomUser:如果您对我的答案中的查询运行EXPLAIN,并对Andomar的答案中的查询运行EXPLAIN,并进行比较,那么这两个执行计划可能非常相似……我们希望EXPLAIN我的答案中的查询将在额外的列中显示“Not exists”(不存在)。如果不关心空值,那么可以用普通的旧相等比较运算符替换
(spaceship)空安全比较运算符。
id username
---- --------
2 foo
3 fee
5 fi
userid appid mainid
------ ----- ------
2 444 888
3 444 1
3 1 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