首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >需要帮助来获得正确的查询mysql数据库php

需要帮助来获得正确的查询mysql数据库php
EN

Stack Overflow用户
提问于 2018-07-19 04:31:03
回答 1查看 34关注 0票数 1

我试图从我的数据库中获取一些JSON数据,但我无法编写正确的SQL查询。

我试过了:

代码语言:javascript
复制
$sql = "SELECT arrondissement AS tName, ("SELECT count(*) FROM fcr_table WHERE arrondissement = 'tName';) as tLength FROM fcr_table GROUP BY name";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result['tName']->fetch_assoc()) {
        echo "name: " .$row['tName']. " " .$row['tLength']. "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();

为了解释更多,这里是我想要实现的一个示例:

代码语言:javascript
复制
+----+-------+-------+
| id | name  | score |
+----+-------+-------+
| 0  | test1 | 1000  |
| 1  | test2 | 2000  |
| 2  | test1 | 3000  |
| 3  | test1 | 5000  |
| 4  | test1 | 1000  |
| 5  | test2 | 3000  |
| 6  | test1 | 7000  |
+----+-------+-------+

我想像这样获取JSON数据:

代码语言:javascript
复制
test1 : count of test1
test2 : count of test2
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-07-19 04:47:59

你可以使用类似这样的东西:

SELECT name AS tName, (SELECT count(*) FROM tests WHERE name=tName) as tLength FROM tests GROUP BY name

如果你不介意化名..。它将允许您在子查询中使用当前名称,从而获得计数。最终,Group by将只留下一个结果,而不是许多重写。如果你进行PHP查询,你将能够访问像$result['tName']$result['tLength']这样的数据

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51410525

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档