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      |
----------------------------------------------------

现在我想查询这个以获取status特定日期的员工。示例:on 的状态id = 1应该2010-02-10返回Leave,而 on2010-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);

4

5 回答 5

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  *
FROM    staff_status
WHERE   id = 1
AND     status_date < '2010-02-10'
ORDER BY    status_date DESC
LIMIT 1
于 2012-08-10T06:10:35.230 回答
1

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

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

...but MySQL doesn't guarantee that the status will be from the row of the MAX(status_date) (in fact, this is almost never the case). So you'll have to take the information you found above, and pull out those records from the original table, matching on id and status_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
    );

This generates a list of ids and statuses for the most recent date found before 2010-02-10:

+------+---------+
| id   | status  |
+------+---------+
|    2 | Working |
|    1 | Leave   |
+------+---------+
2 rows in set (0.01 sec)
于 2012-08-10T06:10:46.810 回答
0

试试这个:

select status 
from staff_status 
where status_date<='2010-03-01'
and id=1
order by status_date desc 
limit 1
于 2012-08-10T06:08:32.867 回答
0

try this:

SELECT IFNULL((SELECT status 
               FROM staff_status 
               WHERE id = 1 AND
                     status_date = '2010-02-10'), 
               "Leave") AS status;
于 2012-08-10T06:11:15.170 回答
0

Surely simply:

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

Would return you "leave"?

于 2012-08-10T06:18:41.797 回答