0

我正在处理状态表,我将显示每个用户的基本信息以及在获取每个用户的最新状态和按用户分组时需要进行哪些过滤。

所以我需要使用的状态表信息是:

  • ID
  • 内容
  • 用户身份

我需要使用的用户信息是:

  • ID
  • 位置ID

所以我想要实现的最终结果是拥有按用户分组的每个用户的最新状态。

我正在使用:

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 的解决方案。

提前致谢。

4

2 回答 2

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;
于 2012-11-21T15:38:52.037 回答
0

This is working for me!

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
于 2012-11-21T15:48:09.980 回答