SQL-按子项(或外键)过滤

时间:2019-02-12 20:57:57

标签: sql

我正在使用SQLite

假设我有2张桌子:

Table 1 - person

| id | username | email          |
| 1  | jdoe     | jd@email.com   | 
| 2  | jane     | jane@email.com |


Table 2 - survey

| id | answered_survey | date       | person.id |
| 1  | no              | 01/01/2019 | 1         |
| 2  | yes             | 01/05/2019 | 1         |
| 3  | no              | 01/06/2019 | 2         |

我想做些类似的事情:在person列中向我显示每个没有yes子代的answered_survey

我一直坚持尝试按“人在Y列中没有X值为孩子的子项”进行查询,而只是不断地“向我展示任何有person的孩子的noanswered_survey

2 个答案:

答案 0 :(得分:3)

带有not exists的一个选项。

select *
from person p
where not exists (select 1 
                  from survey s 
                  where p.id = s.personid
                  and s.answered_survey = 'yes'
                 )

答案 1 :(得分:0)

解决问题的最简单方法是:

SELECT * 
  FROM person 
 WHERE id NOT IN (
    SELECT DISTINCT personid
      FROM survey 
     WHERE answered_survey = 'yes'
);

如果仅需要id,则

SELECT id FROM person 
EXCEPT 
SELECT DISTINCT personid FROM survey WHERE answered_survey = 'yes';

甚至更简单,但是两个SELECT必须返回可比较的记录(相同类型的相同字段数),因此我们必须限制为idpersonid