简体   繁体   English

左外加入,条件是加入者

[英]Left Outer Join with condition on the joinee

Assume I have the following schema 假设我有以下架构

users
+-------+------------+
| Field | Type       |
+-------+------------+
| id    | integer    |
+-------+------------+


posts
+---------+-------------+
| Field   | Type        |
+---------+-------------+
| id      | integer     | 
| user_id | integer     |
| topic   | varchar(255)|
+---------+-------------+

How do I find all the users who have never created a post about Cats? 如何找到从未创建过有关Cats的帖子的所有用户? I tried this query but it doesn't work. 我尝试了此查询,但没有用。

SELECT    users.* 
FROM      users 
LEFT JOIN posts 
ON        users.id = posts.user_id 
WHERE     posts.user_id IS NULL 
AND       posts.topic LIKE 'Cats'

This returns an empty set even when there are users who have never posted about "Cats". 即使有一些从未发布过有关“猫”的用户,这也会返回一个空集。

这将解决您的问题,请尝试并让我知道是否有帮助

SELECT * FROM `users` INNER JOIN posts ON users.id=posts.user_id WHERE users.id NOT IN(SELECT users.id FROM `users` LEFT JOIN posts ON users.id=posts.user_id WHERE posts.topic LIKE '%cats%')
Try to this

SELECT    users.* 
FROM      users 
LEFT JOIN posts 
ON        users.id = posts.user_id 
WHERE     posts.topic NOT LIKE '% Cats %'

这可能会有所帮助: SELECT users.* FROM posts LEFT JOIN users ON posts.user_id = users.id WHERE posts.topic NOT LIKE %Cats% ;

You need to add the LIKE condition to the on clause. 您需要在on子句中添加LIKE条件。

SELECT    users.* 
FROM      users 
LEFT JOIN posts 
ON        users.id = posts.user_id  
AND       posts.topic LIKE 'Cats'
WHERE     posts.user_id IS NULL

Most of the other answers make the mistake of using NOT LIKE in the WHERE clause, but that will return users who have any posts without cats. 其他大多数答案都犯了在WHERE子句中使用NOT LIKE的错误,但这将返回所有帖子中没有猫的用户。 So, if a user posted about cats, but also posted about something not involving cats, they would incorrectly be returned in those queries. 因此,如果用户发布了有关猫的信息,但还发布了有关不涉及猫的信息,则它们将在这些查询中错误地返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM