I have two tables
user:
id,
username
and
app:
userid,
appid,
mainid
I want to display users that dont have a record in this table.I get from address mainId
and appid
.If I run this query
SelectQuery("select User.UserName
from User
INNER JOIN App
ON User.Id = App.UserId
where App.Mainid!= ".$var_MainId." and App.AppId<>".$var_AppId);
It doesnt show the users that may have same userid
and mainid
but not same appid
You could use a not exists
clause. For example, to find users who don't have an app entry with MainId 123 and 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
)
I suggest using an anti-join pattern. But the specification isn't very clear. (Sample data and expected output would go a long ways towards clarifying it.)
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
This query will return rows from u
where there is not a matching row in a
that has the specified values for mainid and appid.
Given contents of user
table as
id username
---- --------
2 foo
3 fee
5 fi
and app
table as
userid appid mainid
------ ----- ------
2 444 888
3 444 1
3 1 888
if we specify a value of 444 for appid
and 888 for mainid
in the query, eg
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
this query would return users 3 and 5. (User 2 will not be returned, because there is a row in app
that matches the specification.)
There are other query patterns that will return an equivalent result. Using a NOT EXISTS (correlated subquery)
pattern is probably the easiest pattern to understand.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.