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

如何通过另一个表获取没有外键的父表的id

  •  0
  • XMehdi01  · 技术社区  · 4 年前

    我有一个表的结构,有很多字段

    表_id 名称表 你的名字 主键 FK
    1. 人 身份证件 主键
    1. 人 名称
    1. 人 年龄
    2. 狗 身份证件 主键
    2. 狗 名称
    2. 狗 物主 fk
    3. 电话 身份证件 主键
    3. 电话 名称
    3. 电话 物主 fk

    如何通过另一个表获取没有外键的父表的id 在这种情况下,预期结果为1

    我试过了

    select distinct table_id from tables_structure where fk!=''
    

    我也试过分组

    select table_id from tables_structure where fk!=''
    group by table_id 
    having fk!=''
    
    1 回复  |  直到 4 年前
        1
  •  1
  •   Chris Schaller    4 年前

    第一个问题是,你正在与一个 空字符串 ,通常我们希望空值由 null 值,所以尝试使用 IS NULL

    select distinct table_id from tables_structure where fk IS NULL
    

    但这不太可能对你有所帮助,你的数据代表着 UNPIVOT 结构,如果使用 COUNT 在你的 HAVING 子句,这里我们甚至不需要比较null,因为 计数 将为我们排除空值!

    select table_id 
    from tables_structure
    group by table_id 
    having COUNT(fk) = 0
    

    如果值真的是空字符串,而不是null,那么我们仍然可以通过处理 '' 作为空值,使用 NULLIF :

    select table_id 
    from tables_structure
    group by table_id 
    having COUNT(NULLIF(fk,'')) = 0
    

    我们不能只是通过过滤 fk <> '' 因为这将修改数据集并返回所有记录。

    你可以用 SUM 超过一小时 CASE 计算 1 或 0 但现在事情变得越来越复杂:

    select table_id 
    from tables_structure
    group by table_id 
    having SUM(CASE fk WHEN '' THEN 0 ELSE 1)) = 0