mysql-两个表从每个用户的第二个表最后跟踪的行中获取记录

zbdgwd5y  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(241)

我有两张table
表a有 usr_id , usr_name , usr_status [1 or 0] 表b有 id, usr_id,tracked_date [Each user can track multiple time] 需要获得每个用户的最后一个轨迹 usr_status = 1 如何通过mysql查询实现?
试过:

SELECT 
    *
FROM
    tableb b
        LEFT JOIN
    tablea a ON a.usr_id = b.usr_id
GROUP BY a.usr_id

有什么建议吗?

col17t5w

col17t5w1#

在派生表中,获取 tracked_dateusr_id 将此结果集联接回主表,以获得相应的行。
尝试:

SELECT 
  ta.*, tb.* 
FROM 
  tablea AS ta 
JOIN tableb AS tb 
  ON tb.user_id = ta.usr_id 
JOIN (
      SELECT 
        user_id, 
        MAX(tracked_date) AS max_tracked_date 
      FROM tableb
      GROUP BY user_id
     ) AS dt 
  ON dt.usr_id = tb.usr_id AND 
     dt.max_tracked_date = tb.tracked_date 
WHERE ta.usr_status = 1

在mysql版本(8.0.2及更高版本)中,我们可以使用窗口函数。使用 Row_Number() 我们可以将行数设置为1,表示行数最高的行 tracked_date 值,在 usr_id . 现在,我们可以将其用作派生表,只考虑行号等于1的行。

SELECT 
  dt.* 
FROM 
(
  SELECT
    ta.*, 
    tb.*, 
    ROW_NUMBER() OVER (PARTITION BY ta.usr_id 
                       ORDER BY tb.tracked_date DESC) AS row_no 
  FROM 
    tablea AS ta 
  JOIN tableb AS tb ON tb.usr_id = ta.usr_id 
  WHERE ta.usr_status = 1
) AS dt 
WHERE dt.row_no = 1

附加:如果您希望获得所有用户( status = 1 ),但不是 tracked_date 尚未进入;笔直的 LEFT JOIN 不会在表和派生表之间工作。
我们必须首先得到对应于最大值的完整行 tracked_date 在单独的派生表中;然后做一个 LEFT JOIN 从users表中,获取所有用户。

SELECT
ta.*, dt2.* 
FROM
  tablea AS ta
LEFT JOIN 
(SELECT tb.*, 
        dt.max_tracked_date
 FROM tableb AS tb
 JOIN (
       SELECT
         usr_id,
         MAX(tracked_date) AS max_tracked_date
       FROM tableb
       GROUP BY usr_id
      ) AS dt
   ON (dt.usr_id = tb.usr_id AND
       dt.max_tracked_date = tb.tracked_date) 
) AS dt2 ON ta.usr_id = dt2.usr_id  
WHERE ta.usr_status = 1

结果

| usr_id | usr_name | usr_status | id  | usr_id | stage | tracked_date        | max_tracked_date    |
| ------ | -------- | ---------- | --- | ------ | ----- | ------------------- | ------------------- |
| 1      | john     | 1          | 2   | 1      | 2     | 2018-11-12 13:12:12 | 2018-11-12 13:12:12 |
| 2      | dave     | 1          | 3   | 2      | 1     | 2018-11-12 13:12:12 | 2018-11-12 13:12:12 |
| 3      | smith    | 1          |     |        |       |                     |                     |

db fiddle视图

相关问题