doumu9799 2015-12-21 22:22
浏览 70
已采纳

从一个表中选择数据,按照另一个表中的数据总和进行排列

A client is looking for a points system to be implemented on her website, I'm struggling to display the users based upon the amount of points collected, I hope somebody may be able to help me out here and point me in the right direction to getting this code to work properly.

I am selecting all data from ap_users and in the code I am also trying to select all data from ap_points although I do not require all the data from either tables, to be specific I only require:

ap_users:
     user_id
     first_name
     last_name
     display_img
     hub_access

ap_points:
     user_id
     points_added

I thought that selecting ALL data may be the easiest route, will let you decide.

I am trying to select and display all users where hub_access = '1' and order by the total points_added by highest first. Points are added separately by rows and need to be added up (which is why I have the sum function).

$sql = "SELECT * FROM `ap_users`, `ap_points` WHERE `hub_access` = '1' ORDER BY sum(points_added) DESC";

I also tried configuring it to be specific tables like:

ap_users.hub_access and ORDER BY sum(ap_points.points_added) but these did not work either.

This current code is either showing no results or a single result with no errors displaying? I'm not sure whether I may need to use some kind of Group By function to connect the user_ids from both tables ?

  • 写回答

1条回答 默认 最新

  • douchushao7799 2015-12-21 23:00
    关注

    SUM is an aggregating function. You should be grouping by user_id if you want the sum for each user_id.

    Something like

    SELECT *, sum(points_added) as sum_points FROM app_users 
    JOIN app_points ON app_users.user_id = app_points.user_id
    WHERE `hub_access` = '1' 
    GROUP BY app_users.user_id
    ORDER BY sum_points;
    

    I have not tested that query, but that should give you an idea of the solution.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 cgictest.cgi文件无法访问
  • ¥20 删除和修改功能无法调用
  • ¥15 kafka topic 所有分副本数修改
  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题
  • ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档
  • ¥50 C++五子棋AI程序编写
  • ¥30 求安卓设备利用一个typeC接口,同时实现向pc一边投屏一边上传数据的解决方案。