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

2つの日付のdiffを求める方法がPostgreSQLとMySQLで異なる

Last updated at Posted at 2020-03-19

TR; DL

PostgreSQL

SELECT 'date(''2020-03-01'') - date(''2020-02-01'')' AS expr,
       date('2020-03-01') - date('2020-02-01') AS days;
expr days
date('2020-03-01') - date('2020-02-01') 29

MySQL

SELECT 'datediff(''2020-03-01'', ''2020-02-01'')' AS expr,
       datediff('2020-03-01', '2020-02-01') AS days
expr days
datediff('2020-03-01', '2020-02-01') 29

ハマったこと

これまで2年超、業務でPostgreSQL (9.6 〜 11)を使ってきたのですが、最近これに加えてMySQL (5.7) も触るようになりました。

そこで、PostgreSQLのノリで日付計算を書いたところ、

-- MySQLで実行
SELECT 'date(''2020-02-29'') - date(''2020-02-01'')' AS expr,
       date('2020-02-29') - date('2020-02-01') AS days
UNION
SELECT 'date(''2020-03-01'') - date(''2020-02-01'')' AS expr,
       date('2020-03-01') - date('2020-02-01') AS days
UNION
SELECT 'date(''2021-03-01'') - date(''2020-02-01'')' AS expr,
       date('2021-03-01') - date('2020-02-01') AS days;
expr days
date('2020-02-29') - date('2020-02-01') 28
date('2020-03-01') - date('2020-02-01') 100
date('2021-03-01') - date('2020-02-01') 10100

時空を超えたようです

同一月であれば問題ないようにも見えますが、月や年を跨ぐと、正しい結果になりません。

1
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
1
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?