MySQL Query获取最后一条记录然后加入

时间:2017-11-29 09:24:15

标签: mysql

假设我有一张这样的表:

表格帐户

id | username 
 1 | myuser123
 2 | secretuser

表格订阅

id | username    | subsStartDate | subsEndDate
 1 | myuser123   |  2017-01-19   | 2017-02-19
 2 | secretuser|  2017-01-19   | 2017-02-19
 3 | myuser123   |  2017-02-19   | 2017-03-19
 4 | secretuser|  2017-02-19   | 2017-03-19

如何获得表subsEndDate中每个用户最新 account。 我正在寻找类似于此的输出:

输出

id | username    | subsStartDate | subsEndDate
 3 | myuser123   |  2017-02-19   | 2017-03-19
 4 | secretuser|  2017-02-19   | 2017-03-19

4 个答案:

答案 0 :(得分:1)

要获得每位用户最新subsEndDate的行,您可以使用以下查询

select a.*
from subscription a
left join subscription b on a.username = b.username
and a.subsEndDate < b.subsEndDate 
where b.id is null

Demo

答案 1 :(得分:1)

订单id不等于订单max_subsEndDate

的情况的变体
SELECT s.*
FROM subscription s
JOIN
  (
    SELECT username,MAX(subsEndDate) max_subsEndDate
    FROM subscription
    GROUP BY username
  ) l
ON s.username=l.username AND s.subsEndDate=l.max_subsEndDate

我的变体(如果订单id等于订单max_subsEndDate

SELECT *
FROM subscription
WHERE id IN(
      SELECT MAX(id)
      FROM subscription
      GROUP BY username
    )

JOIN

的变体
SELECT s.*
FROM subscription s
JOIN
  (
    SELECT MAX(id) max_id
    FROM subscription
    GROUP BY username
  ) l
ON s.id=l.max_id

答案 2 :(得分:1)

SELECT a.* 
  FROM subscription a 
  JOIN 
     ( SELECT username
            , MAX(subsenddate) subsenddate 
         FROM subscription 
        GROUP 
           BY username
     ) b 
    ON b.username = a.username 
   AND b.subsenddate = a.subsenddate;

答案 3 :(得分:0)

这样的事情:

SELECT s.id, s.username, s.subsStartDate, endate as subsEndDate
FROM 
  subscription s
  INNER JOIN 
  (SELECT id, Max(subsEndDate) as endate
    FROM subscription
    GROUP BY id) t ON t.id = s.id