douhuilin1152 2017-05-20 22:40
浏览 61
已采纳

对于每条记录,还要选择具有最高记录值的数据[重复]

This question already has an answer here:

Good evening,

I've got the following two tables:

scripts

*----------------------------*
| user | script_id |   name  |
*----------------------------*
| 408  |    1      | script1 |
| 408  |    3      | script2 |
*----------------------------*

script_versions

*--------------------------------*
| id | version |      script     |
*--------------------------------*
|  1 |    1    | print "script1" |
|  1 |    2    | print "script2" |
|  3 |    0    |  print "other1" |
|  3 |    1    |  print "other2" |
*--------------------------------*

The table scripts contains some general information about a script, for example its name and the user ID of its owner. The table script_versions contains the code of all the different versions per each script.

Now what I want to retrieve from the database:

I want to get the newest version (that means the highest version number) of all scripts for a given user.

For example with the given data the query should return:

Wanted result

*-------------------------------------------------*
| id | version |      script     | user |   name  |
*-------------------------------------------------*
|  1 |    2    | print "script2" | 408  | script1 |
|  3 |    1    |  print "other2" | 408  | script2 |
*-------------------------------------------------*

What I've tried so far

This is my query right now. It does not work as it does not always select the newest version (in fact, it currently always selects the oldest) of all the scripts.

Code:

SELECT * 
  FROM scripts 
  LEFT 
  JOIN 
     ( SELECT * 
         FROM script_versions 
       GROUP 
         BY id 
      ORDER 
          BY version DESC 
      ) AS versions 
          ON scripts.script_id = versions.id 
      WHERE scripts.user = ?

Edit:

This question is not a duplicate of this question, because the mentioned is not about ordering / sorting the result (by the newest version).

</div>
  • 写回答

1条回答 默认 最新

  • duan4739 2017-05-20 22:57
    关注

    Try

    select scripts.id, v.version, v.script, scripts.user, scripts.name
    from scripts s
    inner join
    (select id, max(version) as version from script_versions group by id) aux
    on aux.id = s.script_id
    inner join script_versions v on v.id = aux.id and v.version = aux.version
    where user = ?
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能