2

我有两个 Mysql 表

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 .......");

但是在这种情况下,我无法在父母身上找到这个父母的所有帖子......也许有人可以帮助我......

4

1 回答 1

3

我不确定这是否正是您想要的。看到你的例子,你想Title为每个ID和返回用逗号分隔Name。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                ║
╚════╩═════════╩══════════════════════╝
于 2013-04-05T08:14:35.180 回答