将相关表中的每个颜色产品的尺寸列显示为行?

时间:2014-04-13 12:15:24

标签: mysql

我正在寻找一个查询来组合三个表格。下面是数据库表的简化设计:

Table: Sizes             Table: Colors
+------+------+         +------+-------+
| id   | size |         | id   | color | 
+------+------+         +------+-------+
|    1 |   32 |         |    1 | red   |
|    2 |   34 |         |    2 | blue  |
|    3 |   36 |         |    3 | green |
|    4 |   38 |         |    4 | white |
+------+------+         +------+-------+
Table: Orders 
+------+------+-------+--------+
| id   | size | color | amount |
+------+------+-------+--------+
|    1 |    1 |     1 |      1 |
|    2 |    1 |     2 |      3 |
|    3 |    2 |     2 |      4 |
|    4 |    3 |     2 |      2 |
+------+------+-------+--------+

因此,查询应始终返回所有大小,如果实际存在该颜色的产品,则仅返回颜色。因此,使用上面描述的产品表,我将查询返回以下数据:

+-------+------+------+------+------+
|       | 32   | 34   | 36   | 38   |
+-------+------+------+------+------+
| red   |    1 |    0 |    0 |    0 |
| blue  |    3 |    4 |    2 |    0 |
+-------+------+------+------+------+

当然,查询只返回大小,颜色和数量的组合,PHP脚本将生成它的表。有人可以帮忙吗?提前谢谢!

1 个答案:

答案 0 :(得分:1)

MySQL中没有PIVOT命令(MySQL pivot tables (transform rows to columns)),因此您的查询对于大小是静态的。这就是为什么最好在申请中将其推迟。

如果您只有大小列的有限和小域,那么您可以使用下面发布的以下查询:

mysql> SELECT 
    ->      c.color as color,
    ->      SUM(IF(s.size = 32, o.amount, 0)) as '32',
    ->      SUM(IF(s.size = 34, o.amount, 0)) as '34',
    ->      SUM(IF(s.size = 36, o.amount, 0)) as '36',
    ->      SUM(IF(s.size = 38, o.amount, 0)) as '38'
    ->  FROM `colors` c
    ->  INNER JOIN `order` o
    ->  INNER JOIN `sizes` s
    ->      WHERE c.`id` = o.`color` and s.`id` = o.`size`
    -> GROUP BY color 
    -> ;
+-------+------+------+------+------+
| color | 32   | 34   | 36   | 38   |
+-------+------+------+------+------+
| blue  |    3 |    4 |    2 |    0 |
| red   |    1 |    0 |    0 |    0 |
+-------+------+------+------+------+
2 rows in set (0.04 sec)

正如您在IF条件中所看到的,我使用大小的值,这意味着问题是静态的。我假设所有可能的大小可以是32,34,36,38。

工作演示@ SQL Fiddle

编辑:正如我从开始说的那样如果大小值未知或域很大,那么您在服务器脚本(例如PHP)中推迟透视工作更好,您仍然可以使用以下查询来处理脚本:

SELECT 
     c.color as color,
     s.size,
     o.amount  --Edit: added 
 FROM `colors` c
 INNER JOIN `order` o
 INNER JOIN `sizes` s
     WHERE c.`id` = o.`color` and s.`id` = o.`size`

了解它如何运作@ SQL fiddle