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

时间:2018-01-31 12:30:58

标签: php mysql

我想知道是否可以根据另一个表中的值的总和对表进行排序。我面临的问题如下:我在我的数据库上运行此查询:

<?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();

此后我正在制作这个循环

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

但是表upvotes中不存在列thread_id,thread_content和thread_ownerid。它们只存在于名为threads的表中。这个问题最直接的解决方案是加入。但是,加入的问题是表upvotes中的值都是非唯一的。所以在线程中唯一的thread_id可以存在于5432行中,并且在表格upvotes中提升的列中具有相应的-1 en 1值。

我想解决这个问题的方法是:创建一个带索引/键的数组/字典,将thread_id与其所有upvotes的总和相关联,然后将这个数组/ dict与表线程连接起来。

这是访问所需变量的一种理论方法,但任何允许我访问它们的方式都将非常感激。

非常感谢您在我的问题上投入时间!

1 个答案:

答案 0 :(得分:1)

是的,您可以这样做,但您必须在选择结果中将此值添加为新列,如下所示:

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;

C值将是其他表

中某些值的计数(或总和)
相关问题