0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[自分向けメモ]特定の条件の最後のレコードを出すクエリ

Posted at

自分へ

もういい加減覚えてほしい。何度これを開くんですかね。。

内容

下記のようなテーブルがあった時、type_idとuser_idごとにまとめた最後(最新)のレコードが欲しい時のクエリ
つまり、idが2,4,5,6のレコードが欲しい時

テーブル名:test_table

id user_id type_id value
1 1 1 AAA
2 1 2 BBB
3 2 1 CCC
4 2 2 DDD
5 1 1 EEE
6 2 1 FFF
SELECT
    *
FROM test_table
INNER JOIN (
    SELECT 
        MAX(id)
    FROM test_table
    GROUP BY user_id, type_id
) AS max_id ON test_table.id = max_id.id
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?