如何在同一 table 中使用内部联接

How to use inner join in the same table

我有一个 table 的名字 tnx_line_transfer。架构如下

现在我想生成如下所示的输出

输出

我正在尝试以下查询,但它没有显示正确的输出。这个查询有什么问题

SELECT
    main_tbl.operator_id,
    main_tbl.production_line
FROM
    tnx_line_transfer main_tbl
INNER JOIN (
    SELECT
        operator_id,
        max(date) AS max_date
    FROM
        tnx_line_transfer
    GROUP BY
        operator_id
) temp ON main_tbl.operator_id = temp.operator_id

如果有任何其他替代的简单解决方案,请提前让我know.Thanks。

您错过了与 max_date 一起加入 date 专栏。

SELECT main_tbl.operator_id,
       main_tbl.production_line
FROM   tnx_line_transfer main_tbl
       INNER JOIN (SELECT operator_id,
                          Max(`date`) AS max_date
                   FROM   tnx_line_transfer
                   GROUP  BY operator_id) temp
               ON main_tbl.operator_id = temp.operator_id
                  AND main_tbl.max_date = temp.`date` --here

另一种方法是使用 Sub-Query

SELECT main_tbl.operator_id,
       main_tbl.production_line
FROM   tnx_line_transfer main_tbl
WHERE  `date` = (SELECT Max(`date`)
               FROM   tnx_line_transfer temp
               WHERE  main_tbl.operator_id = temp.operator_id) 

Row_Number 概念在上述情况下派上用场,但不幸的是 Mysql 不支持 Window function's