dqbjvg2518 2015-08-23 10:27
浏览 144

获取MYSQL中重复条目的最新数据

I have a mysql table that contains all the subscribed plan by users. I am trying to create a SELECT statement that will allow me to select for a particular user from the table. Also, if that user have duplicated entries, it will get the latest date of all.

For example, I want to look for John from the table and the date I should get is 2015-09-10.

Subscribed table
ID   FirstName   Date
-------------------------------
1   John        2015-05-30
2   Mary        2014-01-10
3   John        2015-09-10
4   John        2015-03-15
5   Loen        2013-12-11

How should I go about creating the SELECT statement to above the result?

  • 写回答

5条回答 默认 最新

  • douliang2087 2015-08-23 10:32
    关注

    If you just need the first one, you can use LIMIT in conjunction with ORDER BY:

    SELECT * FROM `Subscribed`
      WHERE `FirstName` = 'John' -- Get the name John.
      ORDER BY `Date` DESC       -- Sort results in descending order by Date.
      LIMIT 1                    -- Limit the results to one.
    

    The result will be ordered by date in descending order, and the LIMIT 1 gives out the first row.

    Or to be precise, you can also use Grouping Functions if you need more than one row.

    SELECT `FirstName`, MAX(`Date`) FROM `Subscribed`
      WHERE `FirstName` = 'John'
      GROUP BY `FirstName`
    

    Fiddle: http://www.sqlfiddle.com/#!9/ebb90/1

    评论

报告相同问题?

悬赏问题

  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助