doufen3134 2012-06-29 19:38
浏览 26
已采纳

如何从多个表有效地访问用户数据

Many forums and websites display user information on posts or in tables (when you are looking at more than 1 user)

For example you might have a forum thread and each post on it displays information about the the poster like this:

Name: John Email: email@email.com Posts: 450

They probably have a table for users which is where the name and email are stored, and then a table for posts.

The only think I can think of to do it in one sql statement would be to add 1 to a row (the one that corresponds to the user making the post) in the user table each time the user posted which seems like a bad solution to me.

How do they count the number of posts for each user?

  • 写回答

2条回答 默认 最新

  • duanfu5239 2012-06-29 19:38
    关注

    They use the SQL COUNT() function to dynamically generate the count:

    SELECT COUNT( *) FROM posts WHERE user_id = 1
    

    This will count the number of rows in the posts table which were written by users who match the criteria user_id = 1.

    To do this in one query, you can use a JOIN, and GROUP BY the identifier, like so:

    SELECT username, user_email, COUNT( p.post_id) as num_posts
        FROM users u
        LEFT JOIN posts p
        ON p.user_id = u.user_id
    WHERE u.user_id = 1
    GROUP BY u.user_id
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?