SQL句子停止在SUM()函数

时间:2017-04-14 07:00:25

标签: php mysql sql

我正在尝试制作一个从test_opplegg获取帖子的SQL句子,并在帖子中尝试在表格test_thumbs中检索投票数。在表test_thumbs中,有一列用于post-id(test_thumbs.OId)和test_thumbs.IntValuetest_thumbs.IntValue可以是1或0.而我正在尝试检索test_thumbs.IntValue的总和但是当我运行此代码时,它会在第一篇文章后停止,即使sql-sentence应该打印15个帖子

$sql = $conn->prepare("SELECT test_opplegg.Title, test_opplegg.id as oid, test_opplegg.Desc, test_opplegg.ShortDesc,test_opplegg.Type, test_opplegg.Approved, test_opplegg.Language, test_opplegg.Grade, test_opplegg.UserId, test_opplegg.Link, test_users.id,  test_users.user_Username,  test_users.user_Name
,SUM(test_thumbs.IntValue) ExecCount
                        FROM `test_opplegg` 
                        INNER JOIN test_users ON test_opplegg.UserId = test_users.id
                        INNER JOIN test_thumbs ON test_thumbs.OId = test_opplegg.Id;
                        ;");
//$sql->bind_param('i', $id);
$sql->execute();
   $result = $sql->get_result();/* Get the result */
   $num_of_rows = $result->num_rows;/* Get the number of rows */
if ($num_of_rows > 0) { 
        while ($row = $result->fetch_assoc()) {
            $row_title = $row['Title'] ;
            $row_id = $row['oid'] ;
            $row_desc = $row['Desc'] ;
            $row_shortdesc = $row['ShortDesc'] ;
            $row_grade = $row['Grade'] ;
            $row_type = $row['Type'] ;
            $row_approved = $row['Approved'] ;
            $row_lang = strtolower($row['Language']);
            $row_uid = $row['UserId'] ;
            $row_link = $row['Link'] ;

           $row_countit = "'" . $row['ExecCount'] . "'" ;

            $row_username = $row['user_Username'] ;
            $row_name = $row['user_Name'] ;

如果我删除,SUM(test_thumbs.IntValue) ExecCount一切正常。但是只要我写,SUM(test_thumbs.IntValue) ExecCount,就会打印一行。

所以可以在每个test_opplegg.id上运行SUM() - 函数,对于每一行,我也想要求和()test_thumbs具有相同post-id的所有值。

1 个答案:

答案 0 :(得分:0)

看起来你想念

group by test_opplegg.Id

在查询中

更新:

所以将JOIN更改为

LEFT JOIN test_thumbs ON test_thumbs.OId = test_opplegg.Id

因此,如果test_thumbs中没有相应的记录,则总和为0