2012-08-10 68 views
2

我有以下表命名staff_status,結構和記錄:MySQL查詢得到記錄的具體日期

---------------------------------------------------- 
| id (INT) | status (VARCHAR) | status_date (DATE) | 
---------------------------------------------------- 
| 1  |  Working  | 2009-05-03  | 
| 2  |  Working  | 2009-07-21  | 
| 1  |  Leave  | 2010-02-01  | 
| 1  |  Working  | 2010-02-15  | 
---------------------------------------------------- 

現在我想查詢它來獲取員工的status在特定的日期。示例:id = 12010-02-10狀態應該返回Leave同時2010-03-01應該返回Working

什麼我都沒有成功嘗試:

SELECT t1.status FROM staff_status t1 INNER JOIN (SELECT * FROM staff_status WHERE id = 1 AND status_date < '2010-02-10') t2 ON (t1.id = t2.id AND t1.status_date < t2.status_date);

+1

到目前爲止你做了什麼? – diEcho 2012-08-10 06:05:16

+0

已更新,嘗試查詢 – 2012-08-10 06:07:37

+1

爲什麼你還要加入,如果你只想知道status_date和id時的狀態? – NewInTheBusiness 2012-08-10 06:13:19

回答

2

你可以嘗試一些像

SELECT s.* 
FROM staff_status s INNER JOIN 
     (
      SELECT id, 
        MAX(status_date) status_date 
      FROM staff_status 
      WHERE status_date < '2010-02-10' 
      AND  id = 1 
     ) m ON s.id = m.id 
      AND s.status_date = m.status_date 

Additionaly你可以嘗試一個ORDER BY status_date DESC LIMIT 1

13.2.8. SELECT Syntax

喜歡的東西

SELECT * 
FROM staff_status 
WHERE id = 1 
AND  status_date < '2010-02-10' 
ORDER BY status_date DESC 
LIMIT 1 
+0

我像這種方法。這兩個哪個應該是更好的性能惡習。我想第二個? – 2012-08-10 06:18:16

+0

這可能取決於表上的索引。 – 2012-08-10 06:25:33

0

試試這個:

select status 
from staff_status 
where status_date<='2010-03-01' 
and id=1 
order by status_date desc 
limit 1 
+0

按順序排列的順序應作爲@astander添加 – 2012-08-10 06:22:26

+0

@MuhammadAhmadZafar:對不起,我錯過了搭配 – 2012-08-10 06:23:43

1

首先,你需要在MAX()每個ID的日期:

SELECT id, MAX(status_date) 
FROM staff_status 
WHERE status_date < "2010-02-10" GROUP BY id 

...但MySQL並不保證狀態是從ro MAX(status_date)(實際上,這幾乎從來就不是這樣)。所以你必須把你上面找到的信息,並從原始表拉出的記錄,在idstatus_date匹配:

SELECT id, status 
FROM staff_status 
WHERE 
    (id, status_date) 
    IN 
    (
     SELECT id, MAX(status_date) 
     FROM staff_status 
     WHERE status_date < "2010-02-10" GROUP BY id 
    ); 

這產生的id S和status ES列表爲最近日期2010-02-10前發現:

+------+---------+ 
| id | status | 
+------+---------+ 
| 2 | Working | 
| 1 | Leave | 
+------+---------+ 
2 rows in set (0.01 sec) 
0

試試這個:

SELECT IFNULL((SELECT status 
       FROM staff_status 
       WHERE id = 1 AND 
        status_date = '2010-02-10'), 
       "Leave") AS status; 
+0

你爲什麼添加「離開」? – 2012-08-10 06:43:48

+0

如果記錄不存在於表格中,那麼您將獲得Leave作爲當天的輸出。 – Omesh 2012-08-10 07:00:30

0

Surel Ÿ簡單:

SELECT status FROM staff_status WHERE status_date = '2010-02-10' 

將返回你 「離開」?

+0

不,因爲這樣的記錄不存在 – 2012-08-10 06:19:11

+0

那麼,與2010-02-01。在我的部分錯別字。 – 2012-08-10 06:23:06