MySQL查询以获取特定日期的记录

MySQL查询以获取特定日期的记录,mysql,Mysql,我有一个名为staff_status的下表,其中包含结构和记录: ---------------------------------------------------- | id (INT) | status (VARCHAR) | status_date (DATE) | ---------------------------------------------------- | 1 | Working | 2009-05-03 | | 2

我有一个名为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      |
----------------------------------------------------
现在我想通过查询来获取员工在特定日期的状态。示例:2010-02-10上id=1的状态应返回休假,而2010-03-01上的状态应返回工作

我的尝试没有成功:

从staff_status t1内部联接中选择t1.status,其中id=1,状态日期<'2010-02-10't2,t1.id=t2.id,t1.status日期 试试这个:

select status 
from staff_status 
where status_date<='2010-03-01'
and id=1
order by status_date desc 
limit 1
SELECT IFNULL((SELECT status 
               FROM staff_status 
               WHERE id = 1 AND
                     status_date = '2010-02-10'), 
               "Leave") AS status;

你可以试试类似的东西

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
SELECT  *
FROM    staff_status
WHERE   id = 1
AND     status_date < '2010-02-10'
ORDER BY    status_date DESC
LIMIT 1
此外,您还可以尝试按状态\日期描述限制1订购

差不多

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
SELECT  *
FROM    staff_status
WHERE   id = 1
AND     status_date < '2010-02-10'
ORDER BY    status_date DESC
LIMIT 1

首先,您需要每个id的最大日期:

SELECT id, MAX(status_date)
FROM staff_status
WHERE status_date < "2010-02-10" GROUP BY id
这将生成2010年2月10日之前发现的最近日期的ID和状态列表:

试试这个:

select status 
from staff_status 
where status_date<='2010-03-01'
and id=1
order by status_date desc 
limit 1
SELECT IFNULL((SELECT status 
               FROM staff_status 
               WHERE id = 1 AND
                     status_date = '2010-02-10'), 
               "Leave") AS status;
当然很简单:

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

是否返回您的离开?

已更新尝试的查询如果您知道状态日期和id,您想要的只是状态,您为什么还要加入?NewInBusiness是正确的,您的查询似乎与问题的标题不同。你需要做的就是从staff_status中选择status,其中id=1和date='2010-02-10'。Derek我现在同意NewInBusiness和like astander方法,但你的查询永远不会起作用,因为这样的记录不存在,我不喜欢这种方法。这两者中哪一个应该是性能更好的。我猜是第二个?这可能取决于表中的索引。不,因为这样的记录不存在,2010-02-01。我的输入有误。@MuhammadAhmadZafar:对不起,我打错了。如果记录不在表中,那么您将获得当天的休假作为输出。