我有一个SQL查询,我试图只显示不同的记录,如每个用户订单的最后一个帖子desc。怎么做?我尝试了分组,但它失败了。
SELECT jca.id,
ju.name,
jca.actor,
jca.title as title,
jca.created as postedDate
FROM community_activities jca
left join users ju on jca.actor=ju.id
left join community_users jcu on jcu.userid=ju.id
ORDER BY jca.id, jca.postedDate DESC LIMIT 0 , 50;
id name actor title
200 chandra 12 hello man
201 chandra 12 hey man
202 shayam 13 hello hero
203 chandra 12 hello yoyo
204 kokila 16 yep
205 chandra 12 hello y
206 chandra 12 hello abc
答案 0 :(得分:1)
SELECT
MAX(jca.id), -- just selects maximum of each column ,
DISTINCT ju.name, -- max() may be wrong for your scenario .
MAX(jca.actor),
MAX(jca.title) as title,
MAX(jca.created) as postedDate
FROM
community_activities jca
left join
users ju on jca.actor=ju.id
left join
community_users jcu on jcu.userid=ju.id
GROUP BY
ju.name;
输出:
202 shayam 13 hello hero
204 kokila 16 yep
206 chandra 12 hello abc
答案 1 :(得分:1)
要仅显示每个用户的最新帖子,请创建一个派生表,该表仅包含每个用户的最新帖子ID,并将community_activities
加入该表,因此只会显示这些结果。
SELECT jca.id,
ju.name,
jca.actor,
jca.title as title,
jca.created as postedDate
FROM community_activities jca
JOIN (SELECT MAX(id) max_id
FROM community_activities
GROUP BY actor) t1 on t1.max_id = jca.id
LEFT JOIN users ju on jca.actor=ju.id
LEFT JOIN community_users jcu on jcu.userid=ju.id
ORDER BY jca.id, jca.postedDate DESC LIMIT 0 , 50;
答案 2 :(得分:-1)
SELECT jca.id,
ju.name,
jca.actor,
jca.title AS title,
MAX(jca.created) AS postedDate
FROM community_activities jca
LEFT JOIN users ju ON (jca.actor = ju.id)
LEFT JOIN community_users jcu ON (jcu.userid = ju.id)
ORDER BY jca.created DESC