SELECT single row from child table for each row in parent table

后端 未结 4 1271
轻奢々
轻奢々 2020-12-19 13:07

I am trying to get only one row from child table for each parent row with child fields included, I have been trying with GRUOP BY but with no success :( Here is my initial S

相关标签:
4条回答
  • 2020-12-19 13:44

    You didn't state your DBMS so this is a standard ANSI solution:

    SELECT pID, lastname 
    FROM parent 
      LEFT JOIN (
             SELECT pID, 
                    row_number() over (partition by pid order by cid) as rn
             FROM child
             ) as child 
             ON parent.pID = child.pID and child.rn = 1
    

    Which rows you define as the "first" row is up to you. There is no such as a "first" row unless you sort the rows - that's what the part order by cid does in the partition clause. So if you want something different as the "first" row, you need to change that.

    Btw: there is no need to select all columns from the child table if you don't use them.

    0 讨论(0)
  • 2020-12-19 13:44

    you'll have to replace

    SELECT cID, pID, phone, company, title FROM child
    

    with something returning only one row per pid. What the correct choice is depends on your requriements. The simples is group by:

    SELECT min(cID), pID, min(phone), min(company), min(title) FROM child group by cID
    

    but the different columns will come from different rows so you probably want something like 'the first row' how to implement that depends on the RDBMS you are using, so please add that information to your question.

    0 讨论(0)
  • 2020-12-19 13:46

    "get only one row from child table for each parent row with child fields included"

    That sounds like the child table can have more than one row for the same pID value. And you want only one child row for each pID.

    SELECT pID, Min(cID) AS MinOfcID
    FROM child
    GROUP BY pID;
    

    Join that GROUP BY query back to the child table again to retrieve the other columns for each target cID value. Save this query as qryChild.

    SELECT
        c.pID,
        c.cID,
        c.phone,
        c.company,
        c.title,
        c.address
    FROM
        (
            SELECT pID, Min(cID) AS MinOfcID
            FROM child
            GROUP BY pID
        ) AS map
        INNER JOIN child AS c
        ON c.cID = map.MinOfcID;
    

    Finally, to include lastname values, join the parent table to qryChild.

    0 讨论(0)
  • 2020-12-19 13:53
    SELECT cID ChildID, 
           pID ParentID, 
           phone, 
           company, 
           title, 
           (SELECT lastname FROM parent WHERE id = ParentID) as LastName
    FROM child
    GROUP BY ParentID
    
    0 讨论(0)
提交回复
热议问题