我正在尝试从数据库中获取一些JSON数据,但是我无法编写正确的SQL查询。
我尝试过:
$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();
这里要说明的是我要实现的示例:
+----+-------+-------+
| 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数据:
test1 : count of test1
test2 : count of test2
答案 0 :(得分:1)
您可以使用类似的东西:
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']