大家
我正在开发一个 php 和 mysql 项目,我有一个 SQL 查询,它从我的数据库中选择主题(集合),其中包含用户表中的用户信息以及与每个集合相关的标签,我使用这样的查找表:
select
`collections`.`id` as c_id
, `collections`.`user_id` as c_user_id
, `thumbnail`
, left(`collections`.`description`, 81) as description
, `collections`.`added` as c_added
, `collections`.`views` as c_views
, `collections`.`likes` as c_likes
, `collections`.`title` as c_title
, `users`.`name` as user_name
, `users`.`avatar`
, group_concat(`tags`.`tag_name`) as hashtags
from collections left join collectionstags
on collections.id = collectionstags.collection_id
left join tags on
tags.id = collectionstags.tag_id
inner join users on
`collections`.`user_id` = `users`.`id`
group by collections.id
order by `collections`.`added` DESC
limit 0, 16;
它工作得很好,它返回了我需要的信息,直到我尝试添加另一个左连接以从评论表中获取评论数量:
select
`collections`.`id` as c_id
, `collections`.`user_id` as c_user_id
, `thumbnail`
, left(`collections`.`description`, 81) as description
, `collections`.`added` as c_added
, `collections`.`views` as c_views
, `collections`.`likes` as c_likes
, `collections`.`title` as c_title
, `users`.`name` as user_name
, `users`.`avatar`
, group_concat(`tags`.`tag_name`) as hashtags
, count(`comments`.`id`) as num_comments
from collections left join collectionstags
on collections.id = collectionstags.collection_id
left join tags on
tags.id = collectionstags.tag_id
inner join users on
`collections`.`user_id` = `users`.`id`
left join comments on
`comments`.`collection_id` = `collections`.`id`';
group by collections.id
order by `collections`.`added` DESC
limit 0, 16;
当我添加最后一个连接时,它开始返回每个标签 16 次,而不是一次,例如,而不是返回:
hashtags="nature, river, trees";
它返回:
hashtags="nature, nature, nature, nature, nature, nature, nature, nature, nature, nature, nature, nature, nature, nature, nature, nature, trees,...ect";
最佳答案
请使用 group_concat(DISTINCT(tags
.tag_name
)) 作为主题标签
关于mysql - SQL 查询多次返回 group_concat 函数中的标签字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39313229/