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 5 years have passed since last update.

分析関数(Window関数)を利用してmysql8.0でROW_NUMBER取得

Posted at

分析関数(Window関数)を利用してmysql8.0でROW_NUMBER取得

Mysql8にデーター移行して行数取得でエラー

mysql5.6で問題なかった下記のSQLがmysql8.0で行数取得でエラーが発生。

set @row:=0;
select * 
from 
    (select `id`, @row:=@row+1 as row 
    from `table_a` 
   where `status` = 1 
      and `table_a`.`deleted_at` is null 
      order by `published_day` desc
   ) st 
where `id` = ? limit 1

Mysql8で実行時エラー内容

local.ERROR: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'row from `table_a` where `status` = 1 and

エラー調査

最初はMysql8で下記の書き方が問題なると思い、「Mysql8+row」で調べたら「Window関数」に関する内容が多かった。

@row:=@row+1

ソースを「Window関数」に書き換えて再実行してもエラーは解消されなかった。

select * 
from 
   (select `id`, ROW_NUMBER() OVER (ORDER BY published_day DESC) AS row
   from `table_a` 
   where `status` = 1 and 
      and `table_a`.`deleted_at` is null 
      order by `published_day` desc
   ) st 
where `id` = ? limit 1

エラー原因

Mysql8から「row」が予約語として追加されたのが原因でした。

原因が分かったので下記にソースを変更して再実行したらエラーは解消されました!!

select * 
from 
   (select `id`, ROW_NUMBER() OVER (ORDER BY published_day DESC) AS row_num 
   from `table_a` 
   where `status` = 1 and 
      and `table_a`.`deleted_at` is null 
      order by `published_day` desc
   ) st 
where `id` = ? limit 1

「Window関数」に関して

[1] 基本となるWindow関数
Window関数は、"OVER (PARTITION BY ...)" or "OVER (ORDER BY ...)" をつけて使用します。
OVERの前にくるのは、Window関数に限らず、従来の集約関数(SUM, COUNTなど)でも可能です。
集合関数は後ろにOVER句をつけれれば、分析関数になる。

[2] ROW_NUMBER()
ROW_NUMBER関数は、その名の通り取得した行(レコード)の番号を表示します。
Widnow関数内のORDER BY句で指定されたカラムの順番に沿って、「1」から番号が割り振られます。なお、ROW_NUMBER関数は括弧の中に変数を指定する必要はありません。

従来のMySQLでは行番号を出力する場合に手間がかかっていましたが、ROW_NUMBER()を使えば簡単に取得することができます。

[3] よく使われる関数 : SUM, COUNT, AVG
「Window関数」にはSUM, COUNT, AVGの便利な関数もあり今後機会があったら使いたいと思います。
スクリーンショット 2020-01-07 16.49.28.png

参考サイト

https://wpchiraura.xyz/mysql-80-reserved-word-list/
https://qiita.com/kakuka4430/items/8c66e743800fcb8bc040

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?