我有以下名为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 = 1
上2010-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);
答案 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
像
这样的东西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)
的行(事实上,这几乎不是这种情况)。因此,您必须获取上述信息,并从原始表中提取这些记录,并在id
和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
);
这会为id
之前找到的最近日期生成status
和2010-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'
会让你“离开”吗?