我試過各種不同的方式來查詢這個,但似乎無法得到正是我想要的...我以下使用的工作偉大與1例外。 ..我需要查詢只返回1行PER UNIQUE ID。底部是我期待得到的結果的一個例子。SQL在表中每個唯一ID只返回1行
我當前的查詢:
SELECT
T.id,
T.request_type,
T.created_timestamp,
T.status,
T.subject,
P.id,
P.created_timestamp,
P.created_by_user,
P.post
FROM request_threads T
INNER JOIN request_posts P
ON T.id = P.id
WHERE T.created_by_user = 2
AND P.created_by_user != (
SELECT MAX(P2.created_timestamp)
FROM request_posts P2 WHERE id = T.id
)
ORDER BY P.created_timestamp DESC
我目前的查詢結果:
id request_type created_timestamp status subject id created_timestamp created_by_user post
4 7 2011-11-08 10:50:57.440 7 Request 4 blah black 4 2011-11-14 17:44:16.603 3 Changed status to Closed.
4 7 2011-11-08 10:50:57.440 7 Request 4 blah black 4 2011-11-14 17:44:07.060 3 Test for caps and no punct!
4 7 2011-11-08 10:50:57.440 7 Request 4 blah black 4 2011-11-14 17:43:36.797 3 New formated post with a capital first letter and a period at the end.
4 7 2011-11-08 10:50:57.440 7 Request 4 blah black 4 2011-11-14 13:42:27.707 3 Changed status to Pending. Just testing... test again Blah
2 7 2011-11-07 14:53:01.410 7 Request 2 blah green 2 2011-11-08 13:05:23.183 3 Changed status to Closed.
4 7 2011-11-08 10:50:57.440 7 Request 4 blah black 4 2011-11-08 10:50:57.527 2 This is the 1st yellow post for four
2 7 2011-11-07 14:53:01.410 7 Request 2 blah green 2 2011-11-07 14:53:01.420 2 This is the 1st green post for two
我希望得到的結果:
(注意:我想從request_posts最古老的created_timestamp表)
id request_type created_timestamp status subject id created_timestamp created_by_user post
4 7 2011-11-08 10:50:57.440 7 Request 4 blah black 4 2011-11-14 17:44:16.603 3 Changed status to Closed.
2 7 2011-11-07 14:53:01.410 7 Request 2 blah green 2 2011-11-08 13:05:23.183 3 Changed status to Closed.
是created_timestamp保證是每ID唯一?如果不是你想如何處理關係?如果您希望多個記錄返回關係,請使用galador。當你想任意挑選一個時,請使用Alex的答案。 –