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

后端 未结 4 1290
轻奢々
轻奢々 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: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.

提交回复
热议问题