我在MySQL数据库中有两个表格表A和表格B,我想要两个列的输出列,
table A列a_id integer(5),a_name varchar(20)。
表B列b_id整数(5),b_name varchar(20),a_id varchar(10)。
And tables records are,
select * from a;
+------+--------+
| a_id | a_name |
+------+--------+
| 1 | a1 |
| 2 | a2 |
+------+--------+
select * from b;
+------+--------+------+
| b_id | b_name | a_id |
+------+--------+------+
| 1 | b1 | 1,2 |
| 2 | b2 | 1 |
| 3 | b3 | null |
+------+--------+------+
Now i want to get data which are in b table but also
with a_name column,
+------+--------+-------+
| b_id | b_name | a_name|
+------+--------+-------+
| 1 | b1 | a1,a2 |
| 2 | b2 | a1 |
| 3 | b3 | null |
+------+--------+-------+
如何实现此输出我已尝试使用连接但未获得正确的结果。是否有任何聚合函数可以组合a1,a2值并返回行。非常感谢谢谢。
答案 0 :(得分:0)
这是你可以这样做的,但你应该规范化表b
并且不要存储以逗号分隔的值。
select
b.b_id,
b.b_name,
group_concat(a.a_name) as a_name
from b
left join a on find_in_set(a.a_id,b.a_id) > 0
group by b.b_id