doujianwan7570 2014-03-18 03:01
浏览 41
已采纳

PHP虽然循环不能在SQL中检索使用JOIN LEFT的多行

I'm making a PHP SQL db to catalog short stories. On my index page that shows little excerpts of the stories, I'm trying to display the sql rows from a table (stories) as an unordered list using the while looping function. Ratings for the stories are held in another table and I'm linking it to the 'stories' table using LEFT JOIN and the unique column rows "id" and 'storyid'.

Upon loading, the data displays just fine, however only one SQL row is showing, and my limit is set to 50. The while loop script and sql(close) script flank the list item. No error messages are reporting.

can anyone suggest why only 1 item is showing?

    <?php
            include("db.php");
            $query="SELECT s.*, AVG(r.rank) AS avrank
            FROM (SELECT *
                  FROM stories
                  WHERE id BETWEEN 1 AND 100
                  ORDER BY RAND()
                  LIMIT 50) AS s
            LEFT JOIN ratings AS r ON r.storyidr = s.id";
            $result=mysqli_query($connection,$query);
            ?>

    <ul id="tiles">
      <?php     
            while ($data = mysqli_fetch_assoc($result)):
            $id = $data['id'];
            $author = $data['author'];
            $page_path = $data['page_path'];
            $title = $data['title'];
            $avgrate = $data['avrank'];
            if(is_null($page_path)){$page_path = "#";}
            ?>
      <li>
        <div class="post-info">
          <h3><a href="create_page.php?id=<?php echo $id; ?>"><?php echo $title; ?></a></h3>
          <h3>rating is <?php echo $avgrate; ?>/5</h3>
          <span><a href="categories/<?php echo $category; ?>.php">
          <label> </label>
          </span> </div>
        <div class="post-info-rate-share">
          <form method="POST" action="rating.php?id=<?php echo $id; ?>">
            <fieldset class="rating">
              <legend> Rating: <?php echo $avgrate=round($avgrate,2); ?>/5</legend>
              <input type="radio" id="star5" name="starno" value="5" onclick="this.form.submit()"/>
            </fieldset>
          </form>
        </div>
      </li>
      <?php
            endwhile;
            mysqli_close($connection);
            ?>
    </ul>
  • 写回答

1条回答 默认 最新

  • doutao5419 2014-03-18 03:09
    关注

    You missed the GROUP BY:

    SELECT s.*, AVG(r.rank) AS avrank
    FROM stories s                  
    LEFT JOIN ratings AS r ON r.storyidr = s.id
    WHERE id BETWEEN 1 AND 100
    GROUP BY s.id
    ORDER BY RAND()
    LIMIT 50;
    

    Demo: http://sqlfiddle.com/#!2/7a9fa/9

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

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向