简体   繁体   中英

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? 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.

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. So, if a user posted about cats, but also posted about something not involving cats, they would incorrectly be returned in those queries.

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.

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