MYSQL:在另一个字段中选择具有最大整数值的id

时间:2017-12-20 04:17:43

标签: mysql sql select join inner-join

我有mysql表,它有2个字段如下:

id      item_id
49822   16667
49898   16693
49899   16693
49900   16693
53735   17972
53736   17972
53737   17972

idPKitem_id是另一个字段。

我想用id选择max(item_id)值。换句话说,输出应如下所示

id      item_id
53735   17972
53736   17972
53737   17972

2 个答案:

答案 0 :(得分:4)

SELECT *
FROM YourTable
WHERE item_id = (SELECT max(item_id) FROM YourTable)

答案 1 :(得分:0)

你也可以通过自我加入来获得这个

Started GET "/addresses/search?q=1" for 75.65.92.24 at 2017-12-20 04:35:02 +0000
Cannot render console from 75.65.92.24! Allowed networks: 127.0.0.1, ::1, 
127.0.0.0/127.255.255.255
Processing by AddressesController#search as */*
  Parameters: {"q"=>"1"}
  Address Load (0.2ms)  SELECT  "addresses".* FROM "addresses" ORDER BY 
"addresses"."id" ASC LIMIT ?  [["LIMIT", 1000]]
  CACHE Address Load (0.0ms)  SELECT  "addresses".* FROM "addresses" ORDER 
BY "addresses"."id" ASC LIMIT ?  [["LIMIT", 1000]]
   (0.2ms)  SELECT COUNT(*) FROM "addresses"
3
0
  Rendering addresses/search.js.erb
  Rendered collection of addresses/_address.html.erb [0 times] (0.0ms)
  Rendered addresses/search.js.erb (4.0ms)
Completed 200 OK in 334ms (Views: 8.8ms | ActiveRecord: 1.4ms)

DEMO