选择属性和MAX值

时间:2018-03-09 05:12:12

标签: mysql join

我有通过外键连接的MySql表,如下所示

Person(Driver_id, Name, Address)

Car(Reg_no, Model, Year)

Owns(Driver_id, Reg_no)

Accident(Report_no, Date, Location)

Participated(Report_no, Driver_no, Reg_no, Damage_amt)

Car Values:
KA35F2845 | Fiat Punto   | 2013 |
KA25Y1878 | Audi A4      | 2015 |

Participated Values:
1 | 101| KA35F2845  |      10000 |
2 | 102| KA25Y1878  |      30000 |
  

要求:我想使用Join显示具有最高Damage_amt的汽车模型。

以下是我尝试的代码:

select c.model from car c join (select reg_no,max(damage_amt) from participated) p on c.reg_no=p.reg_no;

此查询选择Car Table中的Maximum value和First值,而不是Maximum value的对应值。

  

预期产量:奥迪A4

     

输出得到:菲亚特Punto

1 个答案:

答案 0 :(得分:0)

我根据您的数据测试了一个查询,结果是Audi A4,请查询

SELECT car.model FROM car join participated on car.reg_no=participated.reg_no WHERE  damage_amt=(SELECT max(damage_amt) FROM participated);