dsfew215211 2015-02-04 23:54
浏览 61
已采纳

Mysql Query不会回显所有结果! PHP

My code goes like this,

$sql = "SELECT Month(time) as Month, Year(time) as Year,
title, COUNT(*) AS total FROM posts GROUP BY Year, Month ORDER BY time DESC";

$stmt = $conn->query($sql);

if ($stmt->num_rows > 0) {
while($row = $stmt->fetch_array()){
  echo "<div class=title>" . $row["title"]. "</div>";
}
}

it is supposed to output 4 titles,

Bellavisa
Mist Neting
Turkey is cool!
Cock of the Rock

but it only outputs

Bellavisa

Turkey is cool!

Cock of the Rock

Note that bellavisa and mist neting are in the same year and month, (setting up an archive list)

EDIT

Here is some of the table data

title "bellavisa" content "yadadada" time "timestamp ..." Author "author"   

title "mist nesting" content "yadadada" time "timestamp ..." Author "author"
  • 写回答

1条回答 默认 最新

  • dongse5528 2015-02-05 00:31
    关注

    Well, title is per post, so to get all the titles you should use no GROUP BY, while COUNT(*) is per month, so to get counts you need to GROUP BY the way you do, so in a simple SELECT you can either select one or another, but not both.

    To select both, you need to use a subquery, something along the lines of

    $sql = "SELECT Month(time) as Month, Year(time) as Year, title, (SELECT COUNT(*) FROM posts WHERE Month(time) = Month AND Year(time) = Year) AS total FROM posts ORDER BY time DESC;";
    

    Effectively, the query selects all the posts, and for each post computes a count. It is not the most efficient way to do that, you can rewrite it using a join, if every post has a unique ID. But for a table with reasonable size this query will work just fine.

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

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序