dongyied24121 2012-06-23 02:30
浏览 86
已采纳

mysql返回每个user_id的总行数

  $sql = "SELECT * FROM books LEFT JOIN users
           ON books.readby=users.user_id WHERE users.email IS NOT NULL";
  $result = mysql_query($sql);
  while($row = mysql_fetch_array($result))
     {
echo $row['readby']. " - read 10 books";
 } //while ends

this is the code I have so far. I am trying to retrieve the number of books read by each user and echo the results. echo the user_id and number of books he/she read books table is like this : id - name - pages - readby the row readby contains the user id.any ideas/suggestions? I was thinking about using count() but Im not sure how to go about doing that.

  • 写回答

2条回答 默认 最新

  • dt614037527 2012-06-23 02:42
    关注

    A subquery can return the count of books read per user. That is left-joined back against the main table to retrieve the other columns about each user.

    Edit The GROUP BY had been omitted...

    SELECT 
      users.*,
      usersread.numread
    FROM 
      users
      /* join all user details against count of books read */
      LEFT JOIN  (
        /* Retrieve user_id (via readby) and count from the books table */
        SELECT 
          readby,
          COUNT(*) AS numread
        FROM  books
        GROUP BY readby
      ) usersread ON users.user_id = usersread.readby
    

    In your PHP then, you can retrieve $row['numread'] after fetching the result.

    // Assuming you already executed the query above and checked errors...
    while($row = mysql_fetch_array($result))
    {
      // don't know the contents of your users table, but assuming there's a 
      // users.name column I used 'name' here...
      echo "{$row['name']} read {$row['numread']} books.";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制