Mysql查询获取对象的总数

时间:2014-01-09 11:44:14

标签: mysql sql

我有一个问题:

SELECT t1.id, 
       t3.title, 
       Count(t2.city_id) AS objectsCount 
FROM   geo_data AS t1 
       INNER JOIN object AS t2 
               ON t1.uid = t2.city_id 
                  AND t2.is_blocked = 0 
       JOIN geo_data_translation AS t3 
         ON t1.id = t3.id 
            AND t3.language_id = 'de' 
WHERE  t1.is_city = 1 
GROUP  BY name; 

结果是:

+-----+------------------------------+--------------+
| id  | title                        | objectsCount |
+-----+------------------------------+--------------+
| 404 | Achim                        |            1 |
|  85 | Ahrensburg                   |            3 |
| 305 | Ahrensfelde                  |            2 |
| 471 | Aichach                      |            1 |
| 377 | Alfeld (Leine)               |            1 |
| 373 | Algermissen                  |            2 |
| 465 | Allershausen                 |            1 |
| 525 | Alsheim                      |            1 |
| 152 | Altenmoor                    |            1 |
| 482 | Anzing                       |            1 |
| 518 | Armsheim                     |            3 |
| 562 | Arnsdorf                     |            1 |
| 109 | Artlenburg                   |            1 |
| 476 | Aschheim                     |            1 |
| 224 | Asendorf                     |            1 |
| 436 | Augusta                      |            1 |
| 447 | Aystetten                    |            1 |
| 360 | Banteln                      |            1 |

我们看到的是一系列具有对象名称的城市。 Achim市有1个物体,Ahrensburg有3个物体等等。

我想要做的是获得所有列出城市的总对象数。 感谢

3 个答案:

答案 0 :(得分:0)

select t1.title,sum(t1.objectscount)as 'total_count' from table1 t1 
group by t1.title

答案 1 :(得分:0)

SELECT
    COUNT(*) AS objectsCount 
FROM
    geo_data AS t1 
    INNER JOIN object AS t2 
        ON  t1.uid         = t2.city_id 
        AND t2.is_blocked  = 0 
    INNER JOIN geo_data_translation AS t3 
        ON  t1.id          = t3.id 
        AND t3.language_id = 'de' 
WHERE
    t1.is_city = 1; 

答案 2 :(得分:0)

试试这个:

SELECT name,
       t1.id, 
       t3.title, 
       Count(t2.city_id) AS objectsCount 
FROM   geo_data AS t1 
       INNER JOIN object AS t2 
               ON t1.uid = t2.city_id 
                  AND t2.is_blocked = 0 
       JOIN geo_data_translation AS t3 
         ON t1.id = t3.id 
            AND t3.language_id = 'de' 
WHERE  t1.is_city = 1 
GROUP  BY name WITH ROLLUP; 

WITH ROLLUP选项会使其添加name = NULL的额外行,其中包含所有计数的总和。

请参阅GROUP BY Modifiers

的文档