正如标题所示,我想列出我的所有博客文章,每篇文章都显示 3 张照片。并非每篇文章都有照片。
结果示例
我的尝试
SELECT a.article_id, a.title, a.content, a.published, t.topic_title, au.firstname, au.lastname,
GROUP_CONCAT(CONVERT(p.photo_id,CHAR(8)) ORDER BY p.photo_id ASC SEPARATOR ';') AS photos
FROM blog_articles a
LEFT JOIN photos p USING (article_id)
LEFT JOIN blog_topics t ON a.topic_id = t.topic_id
LEFT JOIN admins au ON a.author_id = au.admin_id
GROUP BY a.article_id
这会生成一个冒号分隔的照片 ID 列表,就像我想要的那样,但我实际上只需要 3 个,而不是全部。显然我可以在我的应用程序代码中获取 3 个 ID,但我想停止在 MySQL 中收集所有这些数据。这是它产生的结果:
14 This is a blog title 2012-07-09 12;13;14;15;16;17;18;19;20;21;22;23;24;25
但我想要的是:
14 This is a blog title 2012-07-09 12;13;14
对此的任何帮助都会很棒。
最佳答案
您可以使用 substring_index 扩展您的 group_concat
SUBSTRING_INDEX(
GROUP_CONCAT(
CONVERT(p.photo_id,CHAR(8))
ORDER BY p.photo_id ASC
SEPARATOR ';'
),
';',
3
) AS photos
关于MySQL - 每条博客文章记录抓取3张照片记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11435504/