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

MySQL,选择不匹配的引用或其他表中不存在引用

  •  1
  • Krunal  · 技术社区  · 5 年前

    例如。

    table: category
    category_id,    category_name
    1               XYZ_1
    2               XYZ_2
    3               XYZ_3
    4               XYZ_4
    5               XYZ_5
    6               XYZ_6
    
    
    table: type
    type_id,    type_name
    1           A
    2           B
    3           C
    4           D
    
    
    table: type_match
    match_Id,   type_id category_id
    1           2       1
    2           3       1
    3           4       1
    4           1       1
    5           2       2
    6           3       2
    7           2       3       
    8           4       3
    9           2       4
    

    如果type\u id不是3或type\u match表中不存在category\u id,我需要category\u id: 预期结果:

    category_id
    3  // category_id exist in type_match table but not matching type_id = 3
    4  // category_id exist in type_match table but not matching type_id = 3
    5  // category_id does not exist in type_match table
    6  // category_id does not exist in type_match table
    

    请帮忙。

    How to not select rows that does not exists in other table

    1 回复  |  直到 5 年前
        1
  •  0
  •   Nick SamSmith1986    5 年前

    你可以使用 NOT EXISTS type_match 那有一个给定的 category_id 和一个 type_id

    SELECT *
    FROM category c
    WHERE NOT EXISTS (SELECT *
                      FROM type_match t
                      WHERE t.category_id = c.category_id 
                        AND t.type_id = 3
                      )
    

    输出:

    category_id     category_name
    3               XYZ_3
    4               XYZ_4
    5               XYZ_5
    6               XYZ_6
    

    Demo on dbfiddle

        2
  •  -1
  •   Tim Biegeleisen    5 年前

    SELECT c.category_id, c.category_name
    FROM category c
    WHERE NOT EXISTS (SELECT 1 FROM type_match t
                      WHERE t.type_id = t.category_id AND t.category_id = c.category_id);
    

    screen capture of demo link below

    Demo