且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从子表中为父表中的每一行选择单行

更新时间:2023-02-05 11:00:08

从子表中仅为包含父字段的每个父行获取一行"

这听起来像child表对于同一pID值可以有多行.而且,每个pID只希望有一个child行.

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;

再次加入该GROUP BY查询回到child表,以获取每个目标cID值的其他列.将此查询另存为qryChild.

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;

最后,要包含lastname值,请将parent表连接到qryChild.

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