在这种情况下,如何从具有不同where条件和不同net分组条件的同一张表中进行选择?

时间:2019-02-09 23:31:45

标签: php mysql sql

基本上,这是我要实现的目标,但我不知道如何在单个查询中完成,也不知道是否可以在单个查询中完成。

SQL fiddle with example data

查询1:

SELECT 
    cityId, 
    COUNT(cityId) 
FROM 
    data 
WHERE 
    streetId IS NULL 
    AND houseId IS NULL 
GROUP BY cityId

查询2:

SELECT 
    cityId, 
    streetId, 
    COUNT(streetId) 
FROM 
    data 
WHERE 
    streetId IS NOT NULL 
    AND houseId IS NULL 
GROUP BY 
    streetId

查询3:

SELECT 
    cityId, 
    streetId, 
    houseId, 
    COUNT(houseId) 
FROM
    data 
WHERE 
    streetId IS NOT NULL 
    AND houseId IS NOT NULL 
GROUP BY 
    houseId

是否可以在单个查询中执行此操作?

2 个答案:

答案 0 :(得分:1)

好吧,您可以只使用UNION ALL将3个查询的结果汇总在一起。这要求您调整查询,以便它们都返回相同的列。当原始查询中不可用时,我用NULL填充了其他列。

SELECT 
    cityId, 
    NULL street_id, 
    NULL houseId, 
    COUNT(cityId) cnt 
FROM
    data 
WHERE 
    streetId IS NULL 
    AND houseId IS NULL 
GROUP BY 
    cityId
UNION ALL SELECT 
    cityId, 
    streetId, 
    NULL, 
    COUNT(streetId) 
FROM 
    data 
WHERE 
    streetId IS NOT NULL 
    AND houseId IS NULL 
GROUP BY 
    streetId
UNION ALL SELECT 
    cityId, 
    streetId, 
    houseId, 
    COUNT(houseId) 
FROM
    data 
WHERE 
    streetId IS NOT NULL 
    AND houseId IS NOT NULL 
GROUP BY 
    houseId

Results in your db fiddle

cityId  street_id   houseId     cnt
-----------------------------------
1       (null)      (null)      2
2       (null)      (null)      1
2       2           (null)      1
3       3           (null)      5
6       4           3           2

答案 1 :(得分:0)

这不是您想要的吗?

SELECT cityId, streetId, houseId, COUNT(*) 
FROM data 
GROUP BY cityId, streetId, houseId;