2011-06-02 138 views
1

我有一個應用程序使用嵌套集模型類來組織我的數據,但我試圖寫一個查詢,將group_concat我的結果。我知道我需要在某處放置一些子選擇語句,但我無法弄清楚它!GROUP_CONCAT與嵌套集模型

這是我此刻的結構:

表:人

-----------+------------+----------- 
|Person_ID | Name  | Age  | 
-----------+------------+----------- 
| 1   | Mark Vance | 19  | 
| 2   | Michael Tsu| 22  | 
| 3   | Mark Jones | 29  | 
| 4   | Sara Young | 25  | 
-----------+------------+----------- 

表:person_to_group

----+------------+----------- 
|ID | Person_ID | Group_ID | 
----+------------+----------- 
| 1 | 3   | 1   | 
| 2 | 3   | 2   | 
| 3 | 1   | 2   | 
| 4 | 4   | 3   | 
----+------------+----------- 

表:組

----------+--------------+--------------+------------- 
|Group_ID | Group_Name | Group_Left | Group_Right | 
----------+--------------+--------------+------------- 
| 1  | Root   | 1   | 6   | 
| 2  | Node   | 2   | 5   | 
| 3  | Sub Node  | 3   | 4   | 
----------+--------------+--------------+------------- 

我需要呈現索姆ething這樣對我的結果:

//抓住了這個人的group_IDs並把它們放在類標籤...

<li class="2 3">Sara Young is in the Sub Node Group</li> 

注意,雖然薩拉是子節點組中,她依然因爲她是節點的孩子,因此被賦予Node的id。

以下是我正在處理的查詢作爲起點。

SELECT *, GROUP_CONCAT(CAST(gg.Group_ID AS CHAR) SEPARATOR ' ') Group_IDs 
     FROM groups gg 
     LEFT JOIN person_to_group AS t1 ON gg.Group_ID = t1.Group_ID 
     LEFT JOIN person AS t2 ON t2.Person_ID = t1.Person_ID 
     GROUP BY t2.per_ID 
     ORDER BY t2.Name ASC 

任何幫助將不勝感激!

回答

1

以下是我會寫查詢:

SELECT p.Name, 
    GROUP_CONCAT(g.Group_Name) AS Group_List, 
    GROUP_CONCAT(CAST(gg.Group_ID AS CHAR) SEPARATOR ' ') AS Group_ID_List 
FROM person AS p 
INNER JOIN person_to_group AS pg ON p.Person_ID = pg.Person_ID 
INNER JOIN groups AS g ON pg.Group_ID = g.Group_ID 
INNER JOIN groups AS gg ON g.Group_Left BETWEEN gg.Group_Left AND gg.Group_Right 
GROUP BY p.Name 
ORDER BY p.Name ASC 

注意,如果您按人名分組,您還需要GROUP_CONCAT組名列表。根據你的模式,由於多對多的關係,一個人可能屬於多個組。

我也建議一般不要使用SELECT *。只需指定你需要的列。

+0

非常感謝Bill! – Rich 2011-06-02 22:10:29

0

這有點有趣,因爲我在MsSQL和MySql中編程。在SQL中,我使用了稱爲STUFF的函數。在MySQL中,您可以使用一個名爲INSERT的函數。我在MsSQL中嘗試了下面的查詢。沒有MySQL的方便來試用我的查詢。如果我有時間,我會發布查詢的MySQL版本。

DECLARE @person TABLE (Person_ID INT, Name VARCHAR(50), Age INT) 
INSERT INTO @person VALUES 
(1,'Mark Vance',19), 
(2,'Michael Tsu',22), 
(3,'Mark Jones',29), 
(4,'Sara Young',25) 


DECLARE @groups TABLE (Group_ID INT, Group_Name VARCHAR(50), Group_Left INT, Group_Right INT) 
INSERT INTO @groups VALUES 
(1,'Root',1,6), 
(2,'Node',2,5), 
(3,'Sub Node',3,4) 

DECLARE @person_to_group TABLE (ID INT, Person_ID INT, Group_ID INT) 
INSERT INTO @person_to_group VALUES 
(1,3,1), 
(2,3,2), 
(3,1,1), 
(4,4,1), 
(4,1,1) 

SELECT *,STUFF((SELECT ',' + CAST(g.Group_ID AS VARCHAR) FROM @groups g 
    JOIN @person_to_group pg ON g.Group_ID = pg.Group_ID AND pg.Person_ID = a.Person_ID FOR XML PATH('')) , 1, 1, '') FROM @person a 

功能:INSERT(STR,POS,LEN,中newstr) 文檔http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_insert