MySQL “NOT IN” query not working

前端 未结 2 2056
自闭症患者
自闭症患者 2020-12-11 08:57

I have a table with three columns: taxon_id, scientific_name_element_id, and parent_id. I want to find the elements that are children

相关标签:
2条回答
  • 2020-12-11 09:44

    Assuming the parent_id column is NULL (meaning no value is set)

    To select all scientific_name_element_id that have no value for parent_id (meaning parent_id is NULL)

    You do this:

    SELECT scientific_name_element_id
    FROM YOUR_TABLE
    WHERE parent_id IS NULL
    

    This will get you a list of scientific_name_element_id that have no parents.

    0 讨论(0)
  • 2020-12-11 09:51

    Are there any NULLs in taxon_name_element.parent_id?

    The query...

    select taxon_id 
    from taxon_name_element
    where taxon_id not in (
        select parent_id
        from taxon_name_element
    )
    

    ...is equivalent to...

    select taxon_id 
    from taxon_name_element
    where
        taxon_id <> parent_id_1
        AND taxon_id <> parent_id_2
        ...
        AND taxon_id <> parent_id_N
    

    ...where parent_id_X are actual values that are currently in the parent_id column. If even one of them is NULL, the corresponding taxon_id <> parent_id_X expressions will "collapse" into NULL, dragging the whole WHERE expression with it.

    Filter-out NULLs to get what you want:

    select taxon_id 
    from taxon_name_element
    where taxon_id not in (
        select parent_id
        from taxon_name_element
        where parent_id is not null
    )
    
    0 讨论(0)
提交回复
热议问题