MySQL如何获得表中所有所需字段的正确计数

时间:2016-05-31 10:17:56

标签: php mysql sql

假设我有一张桌子:

ID,City1,City2,City3,Country,....(不重要)

该应用程序询问人们他们想住在哪里,让我们说法国。 因此,必须添加至少一个城市,但您可以添加3个最大城市。

例如,我们在表数据中有:

ID    City1    City2    City3    Country   UserID
--------------------------------------------------
1     Paris      /        /      France      1
2     Paris    Nice       /      France      2
3     Paris    Nice       /      France      3
4     Nice     Paris    Lyon     France      4
5     Lyon     Paris    Nice     France      5
6     Cannes   Nice     Paris    France      6
7     Paris    Cannes   Lyon     France      7
--------------------------------------------------

现在,当有人点击法国时,我会在页面上显示所有用户。 然后在上面的用户我希望显示所有城市的数字,如巴黎(n)为 例。

所以,如果我写:

    select City1 as city, count(1) as num 
    from table_c 
   where Country = "France" group by City1;

我得到巴黎(4),但我需要去巴黎(7),因为我还要显示City2和City3,我不知道如何编写这样的SQL语句。

我尝试了许多SQL语句,但后来我得到了几次Paris(n)显示,haw可以做到这一点。如果可以的话?

4 个答案:

答案 0 :(得分:3)

如果CITY1列包含所有城市,那么您只需执行此操作:

SELECT t.city1,sum(t.city1 = t.city2 + t.city1 = t.city3 + t.city1 = t.city4) 
FROM table_c t
WHERE t.Country = "France"
GROUP BY t.city1

如果没有,请使用UNION ALL

SELECT t.city,count(*) FROM (
    SELECT City1 as city FROM table_c WHERE Country = "France"
    UNION ALL
    SELECT City2 FROM table_c WHERE Country = "France"
    UNION ALL
    SELECT City3 FROM table_c WHERE Country = "France"
    UNION ALL
    SELECT City4 FROM table_c WHERE Country = "France") t
GROUP BY t.city

这将为您提供正确的结果

答案 1 :(得分:2)

您可以尝试以下查询:

SELECT      city,
            SUM(cnt) AS num
    FROM    (
        SELECT      City1 AS city,
                    COUNT(*) AS cnt
            FROM    table_c
            WHERE   Country = 'France'
        GROUP BY    City1
        UNION ALL
        SELECT      City2 AS city,
                    COUNT(*) AS cnt
            FROM    table_c
            WHERE   Country = 'France'
        GROUP BY    City2
        UNION ALL
        SELECT      City3 AS city,
                    COUNT(*) AS cnt
            FROM    table_c
            WHERE   Country = 'France'
        GROUP BY    City3
        ) tmp
GROUP BY    tmp.city;

答案 2 :(得分:2)

试试这个;)

select city, count(1)
from (
    select City1 as city
    from table_c 
    where Country = "France"
    union all 
    select City2 as city
    from table_c 
    where Country = "France"
    union all 
    select City3 as city
    from table_c 
    where Country = "France") tmp
group by city

答案 3 :(得分:2)

你可以试试这个sql,让我知道这是否有效

select city, count(1) as num from (
select City1 as city
from table_c
where Country = "France" and city1 is not null
UNION ALL
select City2 as city
from table_c
where Country = "France" and city2 is not null
UNION ALL
select City3 as city
from table_c
where Country = "France" and city3 is not null
) tbl
group by city