我有一个使用嵌套集模型类来组织我的数据的应用程序,但是我正在尝试编写一个将group_concat我的结果的查询。我知道我需要在某处放置一些子选择语句,但我无法理解它!
这是我目前的结构:
表:人 -----------+------------+-----------
|Person_ID | Name | Age |
-----------+------------+-----------
| 1 | Mark Vance | 19 |
| 2 | Michael Tsu| 22 |
| 3 | Mark Jones | 29 |
| 4 | Sara Young | 25 |
-----------+------------+-----------
table: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 |
----------+--------------+--------------+-------------
我需要用我的结果渲染这样的东西:
//抓住这个人的group_ID并将它们放在类标签中......
<li class="2 3">Sara Young is in the Sub Node Group</li>
请注意,尽管Sara位于Sub Node组中,但她仍然被赋予Node的ID,因为她是Node的孩子。
以下是我正在处理的查询作为起点。
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
非常感谢任何帮助!
答案 0 :(得分: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 *
。只需指定所需的列。
答案 1 :(得分: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