2013-04-07 166 views
3

我不明白爲什麼這GROUP_CONCAT不工作,只要外部查詢關注有3行返回,所以我想,要GROUP_CONCAT但它不喜歡它... ...爲什麼這個group_concat不工作?

http://sqlfiddle.com/#!2/24764/3

CREATE TABLE nested_category (
     category_id INT AUTO_INCREMENT PRIMARY KEY, 
     name VARCHAR(20) NOT NULL, 
     lft INT NOT NULL, 
     rgt INT NOT NULL 
); 

INSERT INTO nested_category VALUES(1,'ELECTRONICS',1,20),(2,'TELEVISIONS',2,9),(3,'TUBE',3,4), 
(4,'LCD',5,6),(5,'PLASMA',7,8),(6,'PORTABLE ELECTRONICS',10,19),(7,'MP3 PLAYERS',11,14),(8,'FLASH',12,13), 
(9,'CD PLAYERS',15,16),(10,'2 WAY RADIOS',17,18); 

SELECT GROUP_CONCAT(rs.category_id, ',') 
FROM 
    (
     SELECT node.category_id, node.name, (COUNT(parent.name) - (sub_tree.depth + 1)) AS depth 
     FROM nested_category AS node, 
       nested_category AS parent, 
       nested_category AS sub_parent, 
       (
         SELECT node.category_id, node.name, (COUNT(parent.name) - 1) AS depth 
         FROM nested_category AS node, 
           nested_category AS parent 
         WHERE node.lft BETWEEN parent.lft AND parent.rgt 
          AND node.name = 'PORTABLE ELECTRONICS' 
         GROUP BY node.name 
         ORDER BY node.lft 
       )AS sub_tree 
     WHERE node.lft BETWEEN parent.lft AND parent.rgt 
       AND node.lft BETWEEN sub_parent.lft AND sub_parent.rgt 
       AND sub_parent.name = sub_tree.name 
     GROUP BY node.name 
     HAVING depth = 1 
     ORDER BY node.lft 
    ) as rs 
GROUP BY rs.category_id 

回答

7

兩件事情:

首先:更改GROUP_CONCAT(rs.category_id, ',')GROUP_CONCAT(rs.category_id)

逗號是默認的分隔符,from the docsÿ OU可以看到,如果你想改變的分離,這將是像 GROUP_CONCAT(rs.category_id SEPARATOR '|')

二:刪除上: GROUP BY rs.category_id

如果group by每個category_id,這意味着每個category_id是在它自己的一套和例如group_concat每行只有一個類別。

http://sqlfiddle.com/#!2/24764/7

+0

啊!謝謝。 – user391986 2013-04-07 06:36:04

1

嘗試此查詢

SELECT GROUP_CONCAT(rs.category_id) 
FROM 
    (
     SELECT node.category_id, node.name, (COUNT(parent.name) - (sub_tree.depth + 1)) AS depth 
     FROM nested_category AS node, 
       nested_category AS parent, 
       nested_category AS sub_parent, 
       (
         SELECT node.category_id, node.name, (COUNT(parent.name) - 1) AS depth 
         FROM nested_category AS node, 
           nested_category AS parent 
         WHERE node.lft BETWEEN parent.lft AND parent.rgt 
          AND node.name = 'PORTABLE ELECTRONICS' 
         GROUP BY node.name 
         ORDER BY node.lft 
       )AS sub_tree 
     WHERE node.lft BETWEEN parent.lft AND parent.rgt 
       AND node.lft BETWEEN sub_parent.lft AND sub_parent.rgt 
       AND sub_parent.name = sub_tree.name 
     GROUP BY node.name 
     HAVING depth = 1 
     ORDER BY node.lft 
    ) as rs 

輸出

| GROUP_CONCAT(RS.CATEGORY_ID) | 
-------------------------------- 
|      7,9,10 |