mysql - SQL 查询多次返回 group_concat 函数中的标签字段

标签 mysql sql

大家

我正在开发一个 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/

相关文章:

sql - 获取下一个ID而不插入行

整数字段的 MySQL WHERE 条件返回不正确的值

mysql - SQL查询优化(时间)

MySQL "in"语句

php - 需要计算入住和退房时间之间的总小时数

SQL:避免硬编码或魔数(Magic Number)

mysql - 为什么 MySQL 在尝试插入日期时间 '2019-08-13 19:00:00' 时会出错?

php - Mysql HEX函数解码多字节utf8

MySQL 数据 - 实现分页的最佳方式?

sql - 如何检查序列是否大于某个数字,以及是否在Postgres中进行更改