2011-03-19 77 views
3
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 大衛

回答

-1
SELECT MAX(update_date) FROM table WHERE DATE(update_date) != DATE(NOW()); 
0
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

4
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

1
[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) 
1

不是大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)上的主鍵有所幫助。