0

餐桌顺序

id_order | date    | id_product | id_size | id_gender | name |
   1     |2012-1-1 |     1      |    1    |    1      | john |
   2     |2012-1-1 |     1      |    2    |    1      | mayer|
   3     |2012-1-1 |     2      |    1    |    1      | chris|

表产品

id_shirt |  name   |
   1     |  jeans  |
   2     |  shirt  |
   3     |  jacket |

表格尺寸

id_size  |  size  |
   1     |   S    |
   2     |   M    |
   3     |   L    |
   4     |   XL   |

我会在性别男性的情况下制作这样的作品。

name  |  S  |  M  |  L  |  XL  |
jeans |  2  |     |     |      |
shirt |     |  1  |     |      |

请在codeigniter代码中查询。

4

1 回答 1

3
SELECT  b.name,
        SUM(CASE WHEN c.size = 'S' THEN 1 ELSE 0 END) S,
        SUM(CASE WHEN c.size = 'M' THEN 1 ELSE 0 END) M,
        SUM(CASE WHEN c.size = 'L' THEN 1 ELSE 0 END) L,
        SUM(CASE WHEN c.size = 'XL' THEN 1 ELSE 0 END) XL
FROM    orderTB a
        INNER JOIN productTB b
            ON a.id_product = b.id_shirt
        INNER JOIN sizeTB c
            ON a.id_size = c.id_size
GROUP BY b.name

或者,如果您有未知的大小值,则更喜欢动态 SQL ,例如

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(CASE WHEN c.size = ''',
      size,
      ''' THEN 1 ELSE 0 END) AS ',
      size
    )
  ) INTO @sql
FROM sizeTB;

SET @sql = CONCAT('SELECT  b.name, ', @sql, ' 
                  FROM    orderTB a
                          INNER JOIN productTB b
                              ON a.id_product = b.id_shirt
                          INNER JOIN sizeTB c
                              ON a.id_size = c.id_size
                  GROUP BY b.name');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
于 2013-01-01T09:53:49.573 回答