php - MySQL SELECT 和 order 作为关联数组

标签 php mysql select where-clause

首先感谢观看,我有一个 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/

相关文章:

php - 多次使用绑定(bind)参数

php - 从终端访问 MAMP 的 MySQL

PHP:检查 DateTime 是否未过期

mysql - 我使用 CASE 语句的查询有什么问题

MySQL JOIN 并返回每个域的最长 URL

php - SimpleXML 不返回属性

php - MySQL 事务时序

php - Laravel Schema : Null default, 更新时间戳

php - 更改用户密码

mysql - 如何使用 LIMIT 始终包含第一行