首先感谢观看,我有一个 mysql 问题,老实说我不知道如何解决。如果有人可以帮助我,我将不胜感激。
我的 mysql 数据库中有以下两个表(见下面的链接) http://www.rodneywormsbecher.com/sql-tables.jpg
我想要实现的输出如下:
array ( [0] => category_name [total_userhours] => count(id) userhours [1] => category_name [total_userhours] => count(id) userhours [2] => category_name [total_userhours] => count(id) userhours )
So the first result in the array has the category name and under it, it makes a variable that counts all userhours that have the userhour_category_id.
Thanks in advance, Rodney
/ edit I got 2 working solutions from the replies:
$data = array();
foreach ($Database->customQuery("SELECT * FROM userhour") as $r) {
$cat_id = $r['userhour_category_id'];
$cat_result_set = $Database->fetchSingleArray($Database->customQuery("SELECT * FROM userhour_category WHERE id={$cat_id}"));
$cat_name = $cat_result_set['category_name'];
$count = $Database->fetchSingleArray($Database->customQuery("SELECT COUNT(id) AS total FROM userhour WHERE userhour_category_id={$cat_id}"));
$data[$cat_name] = $count['total'];
}
print_r($data);
$Sql1 = "SELECT c.category_name, count(*) AS total_userhours
FROM `userhour` u
JOIN `userhour_category` c
ON (u.userhour_category_id = c.id)
GROUP BY u.userhour_category_id";
$test = $Database->fetchAllArray($Database->customQuery($Sql1));
print_r($test);
两者都像 Charm 一样工作,但我更喜欢使用 sql 的方式。
输出:
Array ( [Graphic design] => 15 [Web design] => 9 [Newsletter] => 1 ) Array ( [0] => Array ( [category_name] => Web design [total_userhours] => 9 ) [1] => Array ( [category_name] => Graphic design [total_userhours] => 15 ) [2] => Array ( [category_name] => Newsletter [total_userhours] => 1 ) )
谢谢大家
最佳答案
您可以按类别对userhour
进行分组,然后对每个组进行计数:
SELECT c.category_name, count(*) AS total_userhours
FROM `userhour` u
JOIN `userhour_category` c
ON (u.userhour_category_id = c.id)
GROUP BY u.userhour_category_id
我没有测试查询,但它应该可以工作。
关于php - MySQL SELECT 和 order 作为关联数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35917314/