doutan6286 2018-01-31 12:30 采纳率: 100%
浏览 63
已采纳

通过值的总和基于另一个表对表数据进行排序

I was wondering if its possible to sort a table based on the sums of values in another table. The issue im facing is the following: im running this query on my database:

<?php
$sql = "SELECT thread_id, SUM(upvoted) AS upvoted FROM upvotes GROUP BY thread_id ORDER BY upvoted LIMIT :start, {$number_threads}";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':start', (int) $start, PDO::PARAM_INT);
$stmt->execute();

Thereafter im making this while loop

while($result = $stmt->fetch()) {
    // do something with the following variables
    $result['thread_id'];
    $result['thread_content'];
    $result['thread_ownerid'];                        
}

But the columns thread_id, thread_content and thread_ownerid do not exist inside the table upvotes. They only exist inside a table called threads. The most straightforward solution to this problem is joining. However, the problem with joining is that the values in the table upvotes are all non-unique. so a thread_id that is unique in threads can for instance be present in 5432 rows with corresponding -1 en 1 values in the column upvoted in the table upvotes.

My idea to go around this problem is: Make an array/dictionary with indices/keys that link the thread_id with the sum of all its upvotes and then join this array/dict with the table threads.

This is one theoretical way of accesing the desired variables, but any way that allows me to acces them will be greatly appreciated.

Thanks a lot in advance for investing time in my question!

  • 写回答

1条回答 默认 最新

  • douaoj0994 2018-01-31 13:14
    关注

    Yes, you can do it, but you have to add this value as a new column in your select result like this:

    select a.id,a.other,
            (select count(*) 
             FROM table2 AS B 
             WHERE b.id=a.id) AS c
    FROM table1  AS a
    ORDER BY c;
    

    The C value would be the count (or sum) of some values in other table

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

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)