在MySQL中:按年份提取不同的行

时间:2009-09-22 12:53:40

标签: sql mysql

我有一个类似于这的MySQL表:

| id | name | create_date |
---------------------------
| 1  | foo  | 2003-03-11  |
| 2  | goo  | 2003-04-27  |
| 3  | woo  | 2004-10-07  |
| 4  | too  | 2004-12-01  |
| 5  | hoo  | 2005-04-20  |
| 6  | koo  | 2006-01-12  |
| 7  | boo  | 2006-04-17  |
| 8  | moo  | 2006-08-19  |

我想获取所有最新的年度行 - 每年一次。所以在上面的例子中我会得到2,4,5和8。

什么是正确的语法?

5 个答案:

答案 0 :(得分:2)

其他一些答案可能对你有用,但这个简单的查询不需要任何连接

SELECT YEAR(create_date),
(SELECT id ORDER BY create_date DESC LIMIT 1)
FROM mytable
group by YEAR(create_date)

答案 1 :(得分:1)

你可以做点什么

从table_name中选择* 其中create_date在哪里( 选择max(create_date) 来自table_name 按年份分组(create_date))

答案 2 :(得分:0)

SELECT id FROM foo JOIN
  (SELECT YEAR(create_date),MAX(create_date) AS md
     FROM foo
     GROUP BY YEAR(create_date)) as maxes
ON (create_date=md);

如果你在create_date上放一个索引,这将相当快。

答案 3 :(得分:0)

SELECT  mi.*
FROM    (
        SELECT  DISTINCT YEAR(created_date) AS dyear
        FROM    mytable
        ) md
JOIN    mytable mi
ON      mi.id =
        (
        SELECT  id
        FROM    mytable ml
        WHERE   ml.create_date < CAST(CONCAT_WS('.', dyear + 1, 1, 1)) AS DATETIME)
        ORDER BY
                ml.create_date DESC
        LIMIT 1
        )

答案 4 :(得分:0)

select id
from mytable
where not exists (
  select * from mytable as T2
  where T2.id = mytable.id
  and T2.id >= year(created_date) + 1
)