选择最新的日期,但在记录列表

问题描述:

grade_id 
grade_name 
price 
update_date. 

有几个记录对于给定的等级,与diferent日期&价格......在今天的日期较小:选择最新的日期,但在记录列表

grade_id grade_name price update_date (y-m-d) 
1   A   8$  2011-02-01 
1   A   10$  2011-03-01 
1   A   20$  2011-04-01 
2   B   10$  2011-02-01 
2   B   20$  2011-03-01 
2   B   30$  2011-04-01 

?我怎样才能最近更新的价格(但在过去)有选择的查询.. 获得:

1   A   10$  2011-03-01 
2   B   20$  2011-03-01 

,结果......(因为最近的价格,与过去的日期..

THX 大卫

SELECT MAX(update_date) FROM table WHERE DATE(update_date) != DATE(NOW()); 

select t1.* from table as t1 
inner join (
select grade_id,max(update_date) as update_date 
from table where update_date < curdate() group by grade_id) as t2 
on t1.grade_id = t2.grade_id and t1.update_date = t2.update_date 

添加索引表上(grade_id,UPDATE_DATE)

+0

Thwx很多尼克.. – david916 2011-03-19 21:28:41

+0

您的查询作为一个魅力...再次感谢 – david916 2011-03-19 21:29:40

+0

不客气。请将线标记为已回答。 – 2011-03-19 22:35:11

SELECT t1.grade_id, t1.grade_name, t1.price, t1.update_date 
    FROM my_tbl t1 
     LEFT JOIN my_tbl t2 on t2.grade_id = t1.grade_id 
    AND t2.update_date > t1.update_date 
    AND t2.update_date < CURRENT_DATE 
    WHERE t1.update_date < CURRENT_DATE 
    AND t2.grade_id IS NULL 
ORDER BY t1.grade_name 
+0

+1。好一个 :) – 2011-03-19 19:17:03

[email protected]:test> CREATE TABLE t (grade_id INT UNSIGNED NOT NULL, grade_name CHAR(1) NOT NULL, price CHAR(3) NOT NULL, update_date DATE); 
Query OK, 0 rows affected (0.10 sec) 

[email protected]:test> INSERT INTO t VALUES (1, 'A', '8$', '2011-02-01'), (1, 'A', '10$', '2011-03-01'), (1, 'A', '20$', '2011-04-01'), (2, 'B', '10$', '2011-02-01'), (2, 'B', '20$', '2011-03-01'), (2, 'B', '30$', '2011-04-01'); 
Query OK, 6 rows affected (0.13 sec) 
Records: 6 Duplicates: 0 Warnings: 0 

[email protected]:test> SELECT * FROM t; 
+----------+------------+-------+-------------+ 
| grade_id | grade_name | price | update_date | 
+----------+------------+-------+-------------+ 
|  1 | A   | 8$ | 2011-02-01 | 
|  1 | A   | 10$ | 2011-03-01 | 
|  1 | A   | 20$ | 2011-04-01 | 
|  2 | B   | 10$ | 2011-02-01 | 
|  2 | B   | 20$ | 2011-03-01 | 
|  2 | B   | 30$ | 2011-04-01 | 
+----------+------------+-------+-------------+ 
6 rows in set (0.00 sec) 

[email protected]:test> SELECT * FROM (SELECT * FROM t WHERE update_date < DATE(NOW()) ORDER BY update_date DESC) AS `t` GROUP BY grade_id; 
+----------+------------+-------+-------------+ 
| grade_id | grade_name | price | update_date | 
+----------+------------+-------+-------------+ 
|  1 | A   | 10$ | 2011-03-01 | 
|  2 | B   | 20$ | 2011-03-01 | 
+----------+------------+-------+-------------+ 
2 rows in set (0.00 sec) 

不是大NR记录最快的解决方案,但是一个可读的。

select * 
    from table t1 
where update_date = 
     (select max(update_date) 
      from table t2 
      where t2.grade_id = t1.grade_id 
      and t2.update_date < current_date); 

InnoDB表上的(grade_id,update_date)上的主键有所帮助。