我试图从碰巧存储多个状态的表中获取最后一个日期时间记录。我的表看起来像这样:
+---------+--------------------+-------+-------+
|status_id|status_timestamp |User id|Status |
+---------+--------------------+-------+-------+
|1 |2012-02-14 12:04:45 |2 |active |
|2 |2012-02-14 12:14:20 |2 |inactive| <-want that value only
|3 |2013-02-14 12:20:59 |3 |desact |
+---------+--------------------+-------+-------+
SELECT st.Status, st.status_timestamp
FROM status_table as st
INNER JOIN user_profile as up ON st.user_id = up.user_id
WHERE up.username = "usertest";
usertest是user_id 2
我尝试使用max(st.status_timestamp),但我无法让它工作
答案 0 :(得分:0)
一种方法在WHERE
子句中使用相关子查询:
SELECT st.Status, st.status_timestamp
FROM status_table st INNER JOIN
user_profile up
ON st.user_id = up.user_id
WHERE up.username = 'usertest' AND
st.status_timestamp = (SELECT MAX(st2.status_timestamp)
FROM status_table st2
WHERE st2.user_id = st.user_id
);
如果您只想要退回一行,那么更简单的方法是ORDER BY
和LIMIT
:
SELECT st.Status, st.status_timestamp
FROM status_table st INNER JOIN
user_profile up
ON st.user_id = up.user_id
WHERE up.username = 'usertest'
ORDER BY st.status_timestamp DESC
LIMIT 1;