我有两张这样的表:
post_image
image_id| image_name | post_id
1 | hallo.jpg | 1
2 | morning.jpg | 1
3 | sun.jpg | 2
4 | star.jpg | 3
post_table
post_id | post_text
1 | hallo
2 | morning all
3 | sunlight
4 | my night
预期结果是
post_text | image_1 | image_2 | image_3 | image_4 | count_image
hallo | hallo.jpg | morning.jpg | null | null | 2
morning all | sun.jpg | null | null | null | 1
sunlight | star.jpg | null | null | null | 1
my night | null | null | null | null | 0
有人可以帮我,如何使用查询创建输出?
答案 0 :(得分:0)
将值放在单独的列中可能会非常棘手。也许分隔的字符串就足够了:
select p.post_id, p.post_text,
group_concat(image_name) as images,
count(i.post_id) as num_images
from post_table p left join
post_image i
on p.post_id = i.post_id
group by p.post_id, p.post_text;