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

前端之家收集整理的这篇文章主要介绍了php – MySQL如何获得表中所有所需字段的正确计数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我有一张桌子:

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可以做到这一点.如果可以的话?

你可以尝试这个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
原文链接:https://www.f2er.com/php/136383.html

猜你在找的PHP相关文章