代码之家  ›  专栏  ›  技术社区  ›  Pegaz

选择相关表中没有值为的记录的所有行

  •  1
  • Pegaz  · 技术社区  · 6 年前

    我有桌子:

    人员表

    ID  NAME
    1   Matt
    2   Josh
    

    FILE_ID     PERSON_ID   TYPE
    1           1           Photo
    2           2           Text
    3           2           Text
    

    我想返回其他表中没有照片类型文件的所有人。

    在上述场景中,我想返回:

    ID  NAME
    2   Josh
    

    最有效的方法是什么?

    3 回复  |  直到 6 年前
        1
  •  5
  •   Gordon Linoff    6 年前

    我会用 not exists

    select p.*
    from person p
    where not exists (select 1
                      from files f
                      where f.person_id = p.id and f.type = 'Photo'
                     );
    

    为了提高性能,您需要一个索引 files(person_id, type) .

        2
  •  2
  •   Yogesh Sharma    6 年前

    我会用 not exists :

    select p.*
    from person p
    where not exists (select 1 from files f where f.person_id = p.id and f.type = 'photo');
    
        3
  •  2
  •   Zaynul Abadin Tuhin    6 年前

    使用 not in

    select p.*
    from person p
    where p.id not in (select id from Files f where f.type = 'photo');