【问题标题】:Left Join 2 tables, return only records that appears on the 2nd tableLeft Join 2 个表,只返回出现在第 2 个表上的记录
【发布时间】:2012-06-27 11:34:32
【问题描述】:

我要加入 2 个表(table1table2)。

第一个表包含每个记录的唯一globalcid,第二个表包含多次出现的相同globalcid。注意:globalcid是table2对table1的引用字段。

表1

globalcid  / itemdesc
1          / item 1
2          / item 2
3          / item 3
4          / item 4
5          / item 5

表2

globalcid    /  recordcid
1            / 1
1            / 2
2            / 1
3            / 1
3            / 2
3            / 3
5            / 1

我希望查询仅返回 [table1] 中的记录,其中记录在 [table2] GROUP BY table2.globalcid 中,但将返回每个 globalcid 的最后一条记录

在上面的例子中它应该返回

globalcid  / itemdesc  / table2.globalcid
1          / item 1    / 2
2          / item 2    / 1
3          / item 3    / 3
5          / item 5    / 1

【问题讨论】:

    标签: mysql


    【解决方案1】:
    SELECT 
        a.*,
        MAX(b.recordcid) AS maxcid
    FROM 
        table1 a
    INNER JOIN 
        table2 b ON a.globalcid = b.globalcid
    GROUP BY 
        a.globalcid
    

    如果您只关心recordcid 并且不需要该表中的任何其他列,那么这应该没问题。但是,如果表中还有其他列,如下所示:

    globalcid    /  recordcid   /  othercolumn 
    ------------------------------------------
    1            / 1            /  bertrand
    1            / 2            /  centipede
    2            / 1            /  yarn
    3            / 1            /  obviate
    3            / 2            /  hyper
    3            / 3            /  fish
    5            / 1            /  larry
    

    ...那么MAX() 值将不会与othercolumn 中对应的行数据对齐,而是必须将选择的最大值包装在子选择中,如下所示:

    SELECT
        a.*,
        c.recordcid,
        c.othercolumn
    FROM
        table1 a
    INNER JOIN
        (
            SELECT globalcid, MAX(recordcid) AS maxcid
            FROM table2
            GROUP BY globalcid
        ) b ON a.globalcid = b.globalcid
    INNER JOIN
        table2 c ON b.globalcid = c.globalcid AND b.maxcid = c.recordcid
    

    导致:

    globalcid    /  itemdesc    /  recordcid   /  othercolumn 
    ---------------------------------------------------------
    1            /  item1       / 2            /  centipede
    2            /  item2       / 1            /  yarn
    3            /  item3       / 3            /  fish
    5            /  item5       / 1            /  larry
    

    【讨论】:

    • 我需要包含 [table2] 中的另一个字段
    • 太棒了!然后您必须使用我发布的第二个解决方案,只需将c.othercolumn 替换为您希望选择的列。确保在列名前保留别名 c。您可能还需要调整表架构以包含这些列,因为这会对发布的解决方案产生影响。
    【解决方案2】:

    您应该能够使用 inner join 和聚合来实现这一点:

    SELECT table1.globalcid, itemdesc, MAX(recordcid)
    FROM table1 INNER JOIN table2 on table1.globalcid = table2.globalcid
    GROUP BY table1.globalcid, itemdesc
    

    内连接排除 table2 中在 table1 中没有匹配 id 的所有记录。 MAX / GROUP BY 会为每个 globalcid 拉出 recordid 的最大值。

    【讨论】:

    • 这里不选择每一项的最后一条记录,而是选择第一条
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多