PHP mysqli。 ORDER SELECT在一个表之后但从另一个表中SELECT数据?

时间:2015-08-18 20:10:47

标签: php sql mysqli

我有2张桌子。

用户:

pageID
visitorID
last_visit

用户:

userID(this ID and the pageID and visitorID in visitors is bundled to the same exact user)
username
age

我想选择当前登录用户的最后5位访客(ORDER BY last_visit LIMIT 5 in the table visits) 我想从这5个用户的表用户中选择数据。(用户名,年龄等)

我该怎么做?

1 个答案:

答案 0 :(得分:1)

使用JOIN和子查询来获取最后5位访问者。

SELECT u.*
FROM users AS u
JOIN (SELECT visitorId
      FROM visitors AS v
      WHERE v.pageID = $currentUserID
      ORDER BY last_visit
      LIMIT 5) AS v1
ON u.userID = v1.visitorID