mysql组合来自两个表的数据

时间:2015-04-17 09:18:20

标签: mysql sql

不确定这是否可以在DB端进行,但到目前为止我只能得到这个结果:

查询:

SELECT City.city_name "City", PC.subcategory_id "Subcategory", PC.count "count" FROM products_counter PC , Cities City WHERE PC.city_id = City.city_id

+-----------+----------------+-------+
| city_name | subcategory_id | count |
+----------------------------+-------+
| City1     | fruits         | 4     |
| City2     | vegetables     | 4     |
| City1     | meat           | 1     |
+-----------+----------------+-------+

以下是我的两张表:

products_counter:

+-------+---------+----------------+-------+
| ID    | city_id | subcategory_id | count |
+-------+---------+----------------+-------+
|     1 |       1 | fruits         |     4 |
|     2 |       2 | vegetables     |     4 |
|     3 |       2 | meat           |     1 |
+-------+---------+----------------+-------+

城市:

+---------+------------+
| city_id | city_name  |
+---------+------------+
|       1 | City1      |
|       2 | City2      |
|       3 | City3      |
+---------+------------+

这是预期的结果:

+-----------+----------------+-------+
| city_name | subcategory_id | count |
+-----------+----------------+-------+
| City1     | fruits         | 4     |
| City1     | vegetables     | 0     | 
| City1     | meat           | 0     |
| City2     | fruits         | 0     |
| City2     | vegetables     | 4     |
| City1     | meat           | 1     |
| City3     | fruits         | 0     |
| City3     | vegetables     | 0     |
| City3     | meat           | 0     |
+-----------+----------------+-------+

但我不确定如何列出Cities表中的所有城市,如果city_id和subcategory_id相等,则只分配count列。

3 个答案:

答案 0 :(得分:1)

试试这个。

select  c.city_name  ,
        ps.subcategory_id ,
        (   select  `count` 
            from    products_counter 
            where   city_id = c.city_id 
                and subcategory_id = ps.subcategory_id) as 'Count'
from       cities           c
cross join products_counter pc

答案 1 :(得分:1)

您可以使用交叉联接。

SELECT c.city_name, pc.subcategory_id,
IFNULL((select `count` from products_counter where city_id = c.city_id 
                and subcategory_id = pc.subcategory_id),0) as 'Count'
FROM cities c CROSS JOIN products_counter pc

这里的工作示例 - http://sqlfiddle.com/#!9/34c38/16

答案 2 :(得分:1)

select city_name, subcategory_id,
case when cities.city_id = pc.city_id then `count` else 0 end as counter
from cities, products_counter pc