如何在同一个表中使用内连接

时间:2016-02-06 15:36:06

标签: mysql sql inner-join self-join

我的表名为tnx_line_transfer。架构如下

enter image description here

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

输出

enter image description here

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

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

如果有其他替代方案,请告诉我。谢谢。

1 个答案:

答案 0 :(得分:3)

您错过了与date加入max_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