大家,
我正在研究一个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";
答案 0 :(得分:0)
请使用group_concat(DISTINCT(tags
。tag_name
))作为主题标签