我试过各种不同的方式来查询这个,但似乎无法得到正是我想要的...我以下使用的工作伟大与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的答案。 –