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

同一表中有多个键的SQL where子句

  •  1
  • Tom  · 技术社区  · 15 年前

    我有一张有两个键的桌子,我不能把它一分为二。

    第一个键,id是一个计数器。第二个键是parent\u id。

    例如:


    你好,史蒂夫,我是比尔
    你好,比尔?
    3,0,早上好,珍妮丝

    第一个记录是会话的父记录,第二个记录是子记录。

    我遇到的困难是编写一个查询,当您传递任意一个id时,该查询将返回单个会话的两个记录。

    select * from table where id = 2 or parent_id = ( select parent_id from table where id = 2 )
    select * from table where id = 1 or parent_id = ( select parent_id from table where id = 1 )
    

    第一个查询将工作,返回id为1和2的记录。第二个将不会返回,因为它也将返回id为3的行,因为如果传递1,则父id将为零。

    3 回复  |  直到 15 年前
        1
  •  2
  •   p.campbell    15 年前

    • 指定的子记录、其父记录及其同级记录
    • 指定的父记录及其所有单级子记录
     SELECT DISTINCT * FROM 
     (
        --is a child of the specified parent
        SELECT * from table  WHERE parent_id = @SomeID 
        UNION ALL
        -- is the record specified by ID
        SELECT * from table  WHERE ID = @SomeID 
                             --and get the parent itself
                             OR ID = (SELECT parent_id FROM table WHERE ID = @SomeID) 
    
        UNION ALL
        --all siblings with the same parent
        SELECT * FROM table WHERE parent_id = (SELECT parent_id 
                                               FROM table WHERE ID = @SomeID) 
                            AND parent_id>0
    
       ) F
    ORDER BY ID 
    
        2
  •  2
  •   cjk    15 年前

    AND parent_ID <> 0

        3
  •  1
  •   monojohnny    15 年前
    -- I *think* from OP's description , this should do it.
    -- The first SELECT will _always_ bring back a single row (the ID is unique and known to the issuer of the query).
    -- The second SELECT may bring back zero, one or many rows
    -- So (if my understanding is correct) in English:
    -- Bring back the row for the given ID and all (if any) rows which have me as a parent_id.
    -- Rehashed : joining up the IDs from parent->child
    -- Again, not tried...
    SELECT * FROM table parent WHERE parent.id = <id>
    union
    SELECT * FROM table child WHERE child.id=parent.id;