我想要完成的是查询类别表中所有类别的数据,还添加“posts”属性,将该类别中所有帖子的ID列入数组。
数据库表:
'categories' table
+---------+----------+
| id | title |
+---------+----------+
| 100 | "categ1" |
| 101 | "categ2" |
| 102 | "categ3" |
| 103 | "categ4" |
+---------+----------+
'posts' table
+---------+----------+----------+
| id | title | category |
+---------+----------+----------+
| 1 | "abc" | 100 |
| 2 | "def" | 101 |
| 3 | "ghi" | 100 |
| 4 | "jkl" | 102 |
+---------+----------+----------+
输出目标:(json_encode,手动将'categories'添加到顶级)
{
"categories": [
{
"id": 100,
"title": "categ1",
"posts": [1, 3] (Post IDs of those in category 10)
}
{
"id": 102,
"title": "categ2",
"posts": [2]
}
{
"id": 103,
"title": "categ3",
"posts": [4]
}
{
"id": 104,
"title": "categ4",
"posts": []
}
]
}
虽然获取类别的基本查询很简单,但我无法找到根据posts表和帖子类别/类别id关系生成posts属性的方法。
如果有任何不清楚的地方,可以提供更多信息。
答案 0 :(得分:1)
如果我正确理解您的问题,听起来好像您正在寻找GROUP_CONCAT()
:
select c.id, c.title, group_concat(p.id) posts
from categories c
left join posts p on c.id = p.category
group by c.id