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 = ?
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题
  • ¥15 ad5933的I2C
  • ¥15 请问RTX4060的笔记本电脑可以训练yolov5模型吗?
  • ¥15 数学建模求思路及代码
  • ¥50 silvaco GaN HEMT有栅极场板的击穿电压仿真问题