MySQL Query获取特定日期的记录

时间:2012-08-10 06:03:53

标签: mysql

我有以下名为staff_status的表,其中包含结构和记录:

----------------------------------------------------
| 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的状态应返回Leave2010-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);

5 个答案:

答案 0 :(得分: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

另外,您可以尝试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

答案 1 :(得分:1)

首先,你需要每个id的日期的MAX():

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

...但MySQL不保证状态将来自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之前找到的最近日期生成status2010-02-10个es的列表:

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

答案 2 :(得分:0)

试试这个:

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

答案 3 :(得分:0)

试试这个:

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

答案 4 :(得分:0)

当然简单:

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

会让你“离开”吗?