mysql - Left Join 2个表,只返回出现在第2个表上的记录

标签 mysql

我要加入 2 个表(table1table2)。

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

table1

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

table2

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

最佳答案

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 中对应的行数据对齐,相反,您必须将 max 的选择包装在一个像这样子选择:

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

关于mysql - Left Join 2个表,只返回出现在第2个表上的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11202444/

相关文章:

python - 到目前为止还无法让 Flask-MySQL 反射工作

MySQL .. 如果 COUNT 返回任何大于 0 的值,则返回 '1'

mysql - 一对多计算一次查询?

mysql - 选择前后最接近的值

mysql - WEEKOFYEAR() 不是有效的分区函数

mysql - 想要在不使用应用程序的情况下将我的外部 mysql 数据库连接到 Shopify

mysql - 未定义的方法 `add_foreign_key'

mysql - 从 MAMP PRO 手动删除主机

php - Laravel:通过请求验证更新数据不更新数据

javascript - 调用另一个类的函数