简体   繁体   中英

Select rows with Left Outer Join and condition - MySQL

PEOPLE        PEOPLE_FAVS
id            user_id  fav_id
------        -------  ----------
1             1        1
2             1        2
3             1        5
4             2        1
5             2        2
6

I have two tables PEOPLE and PEOPLE_FAVS, I am trying to get all PEOPLE which have not favorited number '5' so it should return

PEOPLE
id
------
2
3
4
5
6

I'm trying with this query:

SELECT `people`.`id`
FROM `people`
LEFT OUTER JOIN `people_favs` ON (`people_favs`.`user_id` = `people`.`id`)
WHERE (`people_favs`.`fav_id` != 5)
GROUP BY `people`.`id`

Here is a SQL Fiddle: http://sqlfiddle.com/#!2/4102b8/3

SELECT p.*
  FROM people p
  LEFT
  JOIN people_favs pf
    ON pf.user_id = p.id
   AND pf.fav_id = 5
 WHERE pf.fav_id IS NULL

http://sqlfiddle.com/#!2/665b6/1

You don't actually need to use an outer join. Outer joins are often used when you want to see ALL rows from one table, regardless of their condition with another. While it would work in this case (as seen by Strawberry's example), you can use the NOT EXISTS operator to check for ids that do not have 5 as a favorite.

As far as I am aware, there is little to no performance difference, but this query is a little shorter. I also feel it is a little more logical, because you aren't really joining information. That's just a personal opinion/thought though.

Try this:

SELECT id
FROM people 
WHERE NOT EXISTS(SELECT id FROM people_favs WHERE fav_id = 5 AND user_id = id);

SQLFiddle example using your data.

Did you try to simply do this:

SELECT DISTINCT `people`.`id`
FROM `people`
JOIN `people_favs` ON (`people_favs`.`user_id` = `people`.`id`)
WHERE (`people_favs`.`fav_id` <> 5)
GROUP BY `people`.`id`

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