[英]Select all from one table but remove if it exists from another table
I currently got a table called Group, it contains a bio and a name and an unique id number on the group.我目前有一个名为 Group 的表,它包含一个个人简介、一个名称以及该组的唯一 ID 号。
Then i also got another table called user_groups which also has an unique id, a user_id and group_id which is the same as the unique number on the group is.然后我还得到了另一个名为 user_groups 的表,它也有一个唯一的 id、一个 user_id 和 group_id,它与组上的唯一编号相同。
So currently im selecting all groups like this:所以目前我选择这样的所有组:
"SELECT * FROM groups WHERE 1"
Which results in all groups.这导致所有组。
So I tried doing this to get all group from the group table except the groups the user got from the other table user_groups所以我尝试这样做以从组表中获取所有组,除了用户从另一个表 user_groups 获得的组
$query = "SELECT *
FROM groups
LEFT OUTER JOIN user_groups
ON groups.id = user_groups.group_id
WHERE user_groups.user_id != '".$_SESSION['id']."'
UNION
SELECT *
FROM groups
RIGHT OUTER JOIN user_groups
ON groups.id = user_groups.group_id
WHERE user_groups.user_id != '".$_SESSION['id']."'";
When I put = to, I get the groups that exists with the user_id from user_groups table but I want all groups that is not linked to an id.当我将 = 放入时,我会从 user_groups 表中获取与 user_id 存在的组,但我想要所有未链接到 id 的组。 How do I acheive this?我如何实现这一目标?
So in my case user with id 15 already "has" group 1 so I dont want to show it for them.:)因此,在我的情况下,ID 为 15 的用户已经“拥有”组 1,所以我不想为他们展示它。:)
I suggest you use NOT EXISTS
which is efficient and convenient for this style of query as it will locate just the rows in the group table where the current user is NOT a member.我建议您使用NOT EXISTS
,这对于这种查询样式来说既高效又方便,因为它只会定位组表中当前用户不是成员的行。
SELECT *
FROM groups
WHERE NOT EXISTS (
SELECT NULL
FROM user_groups
WHERE groups.id = user_groups.group_id
AND user_groups.user_id = $_SESSION[id]
)
Note the subquery used for NOT EXISTS
does not need to return any data through its own select clause;注意用于NOT EXISTS
的子查询不需要通过自己的 select 子句返回任何数据; so select NULL
may be used, but some prefer to use select 1
or select *
instead.所以可以使用select NULL
,但有些人更喜欢使用select 1
或select *
代替。 Note too that because we are using NOT EXISTS we actually need to find the rows that the user IS a match so we use = $_SESSION[id]
instead of <>
or !=
还要注意,因为我们使用的是 NOT EXISTS,所以我们实际上需要找到用户匹配的行,所以我们使用= $_SESSION[id]
而不是<>
或!=
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.