我正在处理状态表我将显示每个用户的基本信息以及在每个用户获取最新状态并按用户分组时出现问题需要进行哪些过滤。
所以我需要使用的状态表信息是:
我需要使用的用户信息是:
所以我想要实现的最终结果是拥有按用户分组的每个用户的最新状态。
我正在使用:
SELECT ID, content
FROM status
WHERE content NOT RLIKE "#[0-9azA-Z]"
AND type = "5"
AND userID IN (
SELECT DISTINCT ID
FROM users
WHERE hometownID = "'.$locationID.'"
OR locationID = "'.$locationID.'"
)
GROUP BY status.userID
ORDER BY addedDate DESC
然后我使用已经添加的用户数组在PHP中按用户分组并排除它们,但这对于扩展和加载更多结果并不理想,所以我想要一个仅限SQL的解决方案。
提前致谢。
答案 0 :(得分:1)
第二次尝试SQL Fiddle
select s.userid, s.content, r.addeddate
from status s
join (select s.userid, max(s.addeddate) as addeddate
from status s
join users u on s.userid = u.id
where u.hometownid = 2
and u.locationid = 3
and s.type = '5'
and s.content not rlike '#[0-9a-zA-Z]'
group by userid) r on s.userid = r.userid
and s.addeddate = r.addeddate;
答案 1 :(得分:0)
这对我有用!
SELECT *
FROM status
NATURAL JOIN (
SELECT userID, MAX(addedDate) as addedDate
FROM status
GROUP BY userID
) AS mostRecent
WHERE userID IN (
SELECT DISTINCT ID
FROM users
WHERE users.locationID = "'.$locationID.'"
OR users.hometownID = "'.$locationID.'"
)
AND status.content NOT RLIKE "#[0-9azA-Z]"
AND type = "5"
#AND userID != "'.$userID.'"
ORDER BY status.addedDate DESC
LIMIT 10