MYSQL - 加入三个表

时间:2013-05-06 16:55:34

标签: php mysql join

我有这个数据库:

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");

我所拥有的是访问访问表,以便我可以获得每个图像的当前总数。

2 个答案:

答案 0 :(得分:0)

在不知道访问表的结构的情况下,我无法提供具体的详细信息,但您应该能够在JOIN之后为用户添加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

答案 1 :(得分: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"