0

我有这个数据库:

Image : id,user_id,[..],created_at
Visit : id,image_id,created_at
user : id,[..]

我有这个查询来获取顶级上传者用户,

$current_month = date('Y-m-d', strtotime("first day of this month")) . ' 23:59:59';
$users = DB::query("SELECT * ,
      COUNT(p.id) as numPics
    FROM
      images p 
    INNER JOIN
      users u
    ON
     p.user_id = u.id
   WHERE 
     p.created_at >= \"$current_month\"
   GROUP BY p.user_id
   ORDER BY numPics DESC LIMIT 10");

我所要做的就是加入访问表,这样我就可以在当前月份获得每个图像的总访问量。

4

2 回答 2

0

在不知道你的访问表结构的情况下,我无法给出具体细节,但你应该能够在for usersJOIN之后添加一个访问子句:JOIN

SELECT *, COUNT(p.id) as numPics, COUNT(v.id) as numVisits
FROM images p 
INNER JOIN users u ON p.user_id = u.id
LEFT JOIN visits v ON v.image_id = p.id AND v.created_at >= "$current_month"
WHERE p.created_at >= "$current_month"
GROUP BY p.user_id
ORDER BY numPics DESC LIMIT 10
于 2013-05-06T16:58:55.600 回答
0

假设您在访问表上有一个 image_id 字段:

SELECT * ,
  COUNT(p.id) as numPics
FROM
  images p 
INNER JOIN
  users u
ON
  p.user_id = u.id

    INNER JOIN visits as v ON v.image_id = p.id

 WHERE 
 p.created_at >= \"$current_month\"
GROUP BY p.user_id
ORDER BY numPics DESC LIMIT 10"
于 2013-05-06T17:00:36.440 回答