我有一张像这样的表:
----------------------------------------
|uID|responseDate|field_01|field_02|etc|
+---+------------+--------+--------+---+
| 1 | 2011-12-02 | yes | no | |
| 2 | 2011-11-25 | no | yes | |
| 1 | 2012-01-02 | no | yes | |
| 2 | 2012-12-01 | no | no | |
| 3 | 2010-01-02 | yes | no | |
+---+------------+--------+--------+---+
我想获得uID和responseDates,对field_01的最新回复为“是” - 所以我的查询应该返回:
------------------
|uID|responseDate|
+---+------------+
| 3 | 2010-01-02 |
+---+------------+
我正在使用内部联接,但不正确。这是我的疑问:
SELECT f.uID, f.responseDate
FROM form_05 as f
INNER JOIN (
SELECT uID, max(responseDate) AS latest_date
FROM form_05
WHERE field_01 = 'yes'
GROUP BY uID ) dmax
ON dmax.uID = f.uID and dmax.latest_date = f.responseDate
ORDER BY f.uID ASC;
然而,返回的是每个uID的最新条目,其中field_01为是,即:
------------------
|uID|responseDate|
+---+------------+
| 1 | 2011-12-02 |
| 3 | 2010-01-02 |
+---+------------+
但我不希望如此。我想这样做只有每个uID的最新条目才有资格进行测试。我该如何重组查询?任何指针都非常感谢。
答案 0 :(得分:2)
尝试一下,如果它不起作用,请告诉我:
select t2.uid, t2.responseDate from t2
left join (
select t1.uid, max(t1.responseDate) as MaxDate from t1
group by t1.uid
) as SubQuery on t2.uid = SubQuery.uid and t2.responseDate = SubQuery.MaxDate
where MaxDate is not null and field_01 = "yes"