获取字段和group_concat的计数

时间:2014-03-30 14:43:54

标签: php mysql

表结构如下     - 表category

的表结构
CREATE TABLE `category` (
  `cat_id` int(10) NOT NULL auto_increment,
  `heading` varchar(255) NOT NULL,
  PRIMARY KEY  (`cat_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;

INSERT INTO `category` (`cat_id`, `heading`) VALUES
(1, 'Fashion'),
(2, 'Kids');

-- --------------------------------------------------------

-- Table structure for table `shop`

CREATE TABLE `shop` (
  `store_id` int(10) NOT NULL auto_increment,
  `shop_name` varchar(255) NOT NULL,
  `cat_id` int(10) NOT NULL,
  `subcat_id` int(10) NOT NULL,
  PRIMARY KEY  (`store_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

INSERT INTO `shop` (`store_id`, `shop_name`, `cat_id`, `subcat_id`) VALUES
(1, 'Test Store', 1, 1),
(2, 'Test Store 1', 1, 1),
(3, 'Another Store', 1, 3);

-- --------------------------------------------------------

-- Table structure for table `subcategory`

CREATE TABLE `subcategory` (
  `subcat_id` int(10) NOT NULL auto_increment,
  `cat_id` int(10) NOT NULL,
  `heading` varchar(255) NOT NULL,
  PRIMARY KEY  (`subcat_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

INSERT INTO `subcategory` (`subcat_id`, `cat_id`, `heading`) VALUES
(1, 1, 'Women'),
(2, 1, 'General'),
(3, 1, 'Men'),
(4, 2, 'Children');

如果我使用以下查询,我会得到以下输出

SELECT
    `category`.`heading` AS `category`
    , `subcategory`.`heading` AS `subcategory`
    , COUNT(`shop`.`subcat_id`) AS cnt
FROM
    `test`.`shop`
    INNER JOIN `test`.`subcategory` 
        ON (`shop`.`subcat_id` = `subcategory`.`subcat_id`)
    INNER JOIN `test`.`category` 
        ON (`shop`.`cat_id` = `category`.`cat_id`)
GROUP BY `shop`.`subcat_id`
HAVING (COUNT(`shop`.`subcat_id`) !='');

类别 子类 CNT
    时尚 女性 2
    时尚 男性 1

但我想将concat分类为下面的子类别

类别 子类
    时尚 女性,2 |男性,1

2 个答案:

答案 0 :(得分:0)

试试这个

SELECT t.category,
GROUP_CONCAT(CONCAT(t.subcategory,',',t.cnt) SEPARATOR '|') `concat`
FROM (
SELECT
    `category`.`heading` AS `category`
    , `subcategory`.`heading` AS `subcategory`
    , COUNT(`shop`.`subcat_id`) AS cnt
FROM
    `shop`
    INNER JOIN `subcategory` 
        ON (`shop`.`subcat_id` = `subcategory`.`subcat_id`)
    INNER JOIN `category` 
        ON (`shop`.`cat_id` = `category`.`cat_id`)
GROUP BY `shop`.`subcat_id`
) t
GROUP BY t.category

注意组concat的默认限制为1024个字符,但可以通过manual

来增加

Fiddle Demo

答案 1 :(得分:0)

不是推荐的输出格式,但使用嵌套子查询很容易完成:

SELECT category,
       group_concat(subcategory, ',', cnt separator '|') as vals
FROM (SELECT c.`heading` AS `category`, sc.`heading` AS `subcategory`,
             COUNT(`shop`.`subcat_id`) AS cnt
      FROM `test`.`shop` s INNER JOIN
           `test`.`subcategory`  sc
           ON s.`subcat_id` = sc.`subcat_id`) INNER JOIN
           `test`.`category` c
           ON s.`cat_id` = c.`cat_id`
      GROUP BY  c.`heading`, sc.`heading`
     ) sc
GROUP BY category;

您的having条款是不必要的。只是检查每个组至少有一行。但有一个,因为你正在使用inner join