2013-04-05 65 views
2

我HEVE两个MySQL表MySQL的父ID循环

participants 

id | name | lastname | 
----------------------------- 
1 | Jon | Bush | 
----------------------------- 
2 | Stephen | Eagle | 

posts 

id | parentid | Title | text 
-------------------------------------- 
1  | 1  | Title1 | Text1 
--------------------------------------- 
2  | 1  | title3 | text2 
--------------------------------------- 
3  |  1 | title4 | text4 
-------------------------------------- 
4  |  2 | title | ttext 

我需要出去表

-------------------------- 
id (1) | Jon | Title1, title3, title4 
------------------------------ 
id (2) | Stephen | title 

我尝试这样做

$result = mysql_query("SELECT name, Title, participants.id, parent FROM aposts, participants WHERE paricipants.id = parent.parent group by last_name ORDER BY ......."); 

但在这个CAS我无法得到循环在父母出去这个家长的所有帖子...也许有人可以帮助我....

回答

3

我不知道这是否正是你想要的。看到你的例子,你想返回Title,用逗号分隔,每IDName。 MySQL有一个称为GROUP_CONCAT的内建函数,它连接行而不是列。

SELECT a.ID, a.Name, 
     GROUP_CONCAT(b.Title) TitleList 
FROM participants a 
     INNER JOIN posts b 
      ON a.ID = b.parentID 
GROUP BY a.ID, a.Name 

输出

╔════╦═════════╦══════════════════════╗ 
║ ID ║ NAME ║  TITLELIST  ║ 
╠════╬═════════╬══════════════════════╣ 
║ 1 ║ Jon  ║ Title1,title3,title4 ║ 
║ 2 ║ Stephen ║ title    ║ 
╚════╩═════════╩══════════════════════╝ 
+0

谢谢!它工作炉排! :D – Arvix 2013-04-05 08:22:38

+0

不客气':D'欢迎来到堆栈溢出! – 2013-04-05 08:23:21

+0

好:)再次感谢:) – Arvix 2013-04-05 08:35:58