简体   繁体   English

MySQL 中 select 闰年的查询条件

[英]Query condition for select leap years in MySQL

I have a year column in one of my table and i need to find those years which are leap year in MySQL.我的一张表中有一个年份列,我需要在 MySQL 中找到闰年 The table name is 'Movie' and I have a particular year and title column in it.表名是“电影”,我有一个特定的年份和标题列。 How to find the movies in leap year in SQL query?如何在 SQL 查询中找到闰年的电影?

I wrote the above query but got the year 'I 2009' in my answer.我写了上面的查询,但在我的回答中得到了“I 2009”的年份。

SELECT year, title from Movie where year%4=0 AND (year%100!=0 OR year%400=0)

The head of the data is like this:数据的头部是这样的:

    title                       Year
0   The Avengers                2012
1   Captain America: Civil War  2016
2   Lion                        2016
3   Slumdog Millionaire         2008
4   2012                      I 2009
SELECT @year,
       DAY(CONCAT(@year, '-03-01') - INTERVAL 1 DAY) = 29 AS is_leap;

or或者

SELECT @year,
       !MOD(@year, 4) - !MOD(@year, 100) + !MOD(@year, 400) AS is_leap;

Accordingly因此

SELECT year, title 
FROM Movie 
WHERE DAY(CONCAT(year, '-03-01') - INTERVAL 1 DAY) = 29

or或者

SELECT year, title 
FROM Movie 
WHERE !MOD(year, 4) - !MOD(year, 100) + !MOD(year, 400)

For all years when there are movies, this suffices:对于有电影的所有年份,这就足够了:

where year % 4 = 0 

The more exact expression is:更准确的表达是:

where (year % 4 = 0 and year % 100 <> 0) or
      (year % 400 = 0)

IN is not appropriate for this condition. IN不适用于这种情况。

Is the data type of the year column a character type?年份列的数据类型是字符类型吗? By using ceil and cast functions, it checks whether it is in numerical format.通过使用 ceil 和 cast 函数,它检查它是否为数字格式。

SELECT year, title from Movie where year%4=0 AND (year%100!=0 OR year%400=0) AND year=cast(ceil(year) as char);

4 2012 I 2009 4 2012 年我 2009 年

It may be an application problem.可能是应用问题。 If the data of "2012" that matched the conditions of the leap year is in the year column, and the data of the title column is NULL, so the title column is misaligned and the year column output like it.如果符合闰年条件的“2012”的数据在年份列,而标题列的数据是NULL,那么标题列错位,年份列output就好了。 If above, I think that 'I ' is incorrect data output by referring to the area outside the range.如果以上,我认为'I'是不正确的数据 output 参考范围之外的区域。

Need to format the Year column and then check the Leap Year condition.需要格式化年份列,然后检查闰年条件。

WHERE (
(
   CAST(SUBSTR(TRIM(year),-4) AS INTEGER)%4=0 
   AND 
   CAST(SUBSTR(TRIM(year),-4) AS INTEGER)%100!=0
)

OR 
(
 CAST(SUBSTR(TRIM(year),-4) AS INTEGER)%100=0 
 AND 
 CAST(SUBSTR(TRIM(year),-4) AS INTEGER)%400=0)
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM