3桌之间的特殊连接

时间:2015-08-31 12:13:07

标签: mysql sql

我创建了3个mysql表:

表'city':包含城市

i.e   |  name  |  category_name  |  city_name  |
      +========+=================+=============+
      | shop_1 |   category_2    |    Rome     |
      +--------+-----------------+-------------|
      | shop_2 |   category_2    |    Rome     |
      +--------+-----------------+-------------+
      | shop_3 |   category_1    |    Paris    |
      +--------+-----------------+-------------+

表'类别':包含类别

|        ||   category_1   |  category_2 |
+========++================+=============+
| Athens ||        0       |      0      |
+--------++----------------+-------------|
| Rome   ||        0       |      2      |
+--------++----------------+-------------+
| Paris  ||        1       |      0      |
+--------++----------------+-------------+

表'商店':包含商店

mysqli_fetch_assoc($result);

我正在尝试创建一个允许我创建以下html数组的单个查询(显示按类别分组的每个城市中有多少商店):

mysqli_fetch_array($result);

提前谢谢你, Giannis

3 个答案:

答案 0 :(得分:1)

试试这个

select c.name,
sum(case when s.category_name='category_1' then 1 else 0 end) as categoty_1,
sum(case when s.category_name='category_2' then 1 else 0 end) as categoty_2
from city as c left join shops as s on c.name=s,city_name
group by c.name

答案 1 :(得分:0)

调查一下     SQL select data from multiple tables表/ 32249225?noredirect = 1#comment52417831_32249225

答案 2 :(得分:0)

尝试:

select Name, isnull([category_1],0), isnull([category_2],0) from
(
    select city.name as Name, category.name as Category, count(category.name) as   [Count]
    from city left join shops on shops.city_name = city.name
    left join category on category.name =  shops.category_name
    group by  city.name, category.name
) as PivotSource
pivot 
(
    sum([Count]) for Category in ([category_1], [category_2])
) as PivotTable