結果制限

記事の内容

概要

LIMIT句は、SELECT文で結果セットから取得する行数を制限するために使用されます。

LIMIT
記述

LIMIT 件数

mysql> SELECT * FROM informations;
+----+------------+---------------------+---------------------+
| id | name       | created_at          | updated_at          |
+----+------------+---------------------+---------------------+
|  1 | test info1 | 2024-04-01 00:01:00 | 2024-04-01 00:01:00 |
|  2 | test info2 | 2024-04-01 00:02:00 | 2024-04-01 00:02:00 |
|  3 | test info3 | 2024-04-01 00:03:00 | 2024-04-01 00:03:00 |
|  4 | test info4 | 2024-04-01 00:04:00 | 2024-04-01 00:04:00 |
+----+------------+---------------------+---------------------+
4 rows in set (0.00 sec)

【取得件数を制限】
mysql> SELECT * FROM informations LIMIT 2;
+----+------------+---------------------+---------------------+
| id | name       | created_at          | updated_at          |
+----+------------+---------------------+---------------------+
|  1 | test info1 | 2024-04-01 00:01:00 | 2024-04-01 00:01:00 |
|  2 | test info2 | 2024-04-01 00:02:00 | 2024-04-01 00:02:00 |
+----+------------+---------------------+---------------------+
2 rows in set (0.00 sec)

開始位置を指定

LIMIT OFFSET
記述

LIMIT 件数 OFFSET 開始位置

mysql> SELECT * FROM informations;
+----+------------+---------------------+---------------------+
| id | name       | created_at          | updated_at          |
+----+------------+---------------------+---------------------+
|  1 | test info1 | 2024-04-01 00:01:00 | 2024-04-01 00:01:00 |
|  2 | test info2 | 2024-04-01 00:02:00 | 2024-04-01 00:02:00 |
|  3 | test info3 | 2024-04-01 00:03:00 | 2024-04-01 00:03:00 |
|  4 | test info4 | 2024-04-01 00:04:00 | 2024-04-01 00:04:00 |
+----+------------+---------------------+---------------------+
4 rows in set (0.00 sec)

【取得件数を制限】
mysql> SELECT * FROM informations LIMIT 2 OFFSET 2;
+----+------------+---------------------+---------------------+
| id | name       | created_at          | updated_at          |
+----+------------+---------------------+---------------------+
|  3 | test info3 | 2024-04-01 00:03:00 | 2024-04-01 00:03:00 |
|  4 | test info4 | 2024-04-01 00:04:00 | 2024-04-01 00:04:00 |
+----+------------+---------------------+---------------------+
2 rows in set (0.01 sec)
記事の内容
閉じる