0

我有 3 个表项,item_sizes,这些字段的大小:

items
id
name

item_sizes
item_id
size_id

sizes
id
size

尺寸具有以下值,例如:S、M、XL、XXL 等

item_id   |   name   |   S   |   M   |  XL  ...
--------------------------------------------
1             shirt      1       0      1
2             dress      0       1      1
3             jacket     1       1      1  

等等。值 1 表示此项目具有此大小。是否有可能做到这一点?

4

1 回答 1

1
SELECT  a.id,
        a.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`,
        SUM(CASE WHEN c.size = 'XXL' THEN 1 ELSE 0 END) `XXL`
FROM    items a
        LEFT JOIN item_sizes b
            ON a.id = b.item_id
        LEFT JOIN sizes c
            ON b.size_ID = c.id
GROUP   BY a.id, a.name

利用PreparedStatament

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

SET @sql = CONCAT('SELECT  a.id,
                           a.name, ', @sql, ' 
                  FROM    items a
                          LEFT JOIN item_sizes b
                              ON a.id = b.item_id
                          LEFT JOIN sizes c
                              ON b.size_ID = c.id
                  GROUP   BY a.id, a.name');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
于 2013-02-01T09:30:21.600 回答