简体   繁体   English

选择具有左外部联接和条件的行-MySQL

[英]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和PEOPLE_FAVS,我试图获取所有不喜欢数字'5'的PEOPLE,所以它应该返回

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 这是一个SQL提琴: 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 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. 尽管在这种情况下它可以工作(如Strawberry的示例所示),但是您可以使用NOT EXISTS运算符来检查不喜欢5的id。

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. SQLFiddle示例使用您的数据。

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`

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

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