[英]How can I combine two tables and group the results of one table?
I want to combine two tables. 我想合并两个表。
table list
: 表格list
:
| id | day |
|:-----|------------:|
| 1 | monday |
| | |
| | |
|:-----|------------:|
| 2 | tuesday |
| | |
table animals
: 餐桌animals
:
| id | animal | list_id |
|:-----|------------:|:----------:|
| 1 | cat | 1 |
|:-----|------------:|:----------:|
| 2 | bird | 1 |
|:-----|------------:|:----------:|
| 3 | monkey | 1 |
|:-----|------------:|:----------:|
| 4 | frog | 2 |
|:-----|------------:|:----------:|
| 5 | dog | 2 |
|:-----|------------:|:----------:|
Here is my approach: 这是我的方法:
$animals = $db->query('SELECT *,
GROUP_CONCAT(animals.animal SEPARATOR " <br> ") AS animals
FROM list
LEFT JOIN animals ON list.id=animals.list_id
')->fetchAll(PDO::FETCH_ASSOC);
This is my desired result: 这是我想要的结果:
| id | day | animal |
|:-----|------------:|:------------:|
| 1 | monday | cat |
| | | bird |
| | | monkey |
|:-----|------------:|:------------:|
| 2 | tuesday | frog
| | | dog
But the result I actually get is: 但是我实际得到的结果是:
| id | day | animal |
|:-----|------------:|:------------:|
| 1 | monday | cat |
| | | bird |
| | | monkey |
| | | frog
| | | dog
You want to merge all the animals with same list_id
hence you need to use Group by
with list_id
. 您要合并所有具有相同list_id
的动物,因此需要将Group by
与list_id
一起使用。 Group_concat()
will concat all the results for each group. Group_concat()
将Group_concat()
每个组的所有结果。 Hence, following query should work: 因此,以下查询应该起作用:
$animals = $db->query('SELECT l.*,
GROUP_CONCAT(animals.animal SEPARATOR " <br> ") AS animals
FROM list l
LEFT JOIN animals ON list.id=animals.list_id
group by animals.list_id // Added statement
')->fetchAll(PDO::FETCH_ASSOC);
Hope it helps! 希望能帮助到你!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.