mysql GROUP_CONCAT DISTINCT 多列

mysql GROUP_CONCAT DISTINCT multiple columns(mysql GROUP_CONCAT DISTINCT 多列)
本文介绍了mysql GROUP_CONCAT DISTINCT 多列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个博客帖子的标签字段.标签具有唯一 ID,但其 displayName 可能重复.我想要的是一个选择帖子的查询,并且在 all_tags 字段中我们得到一对 (id,displayName) 是这样的:

I have a tag field for a blog posts. tags have unique id but their displayName might be duplicated. What I want is a query that selects posts and in all_tags field we get couples of (id,displayName) is this way:

id1,name1;id2,name2;id3,name3

我的查询如下:

select ....
CONCAT_WS(';', DISTINCT (CONCAT_WS(',',tags.id,tags.displayName))) AS all_tags
Join ...post content ...
Join ...post_tags ...
Join ...tags ...
ORDER BY posts.id

这行导致问题:

CONCAT_WS(';', DISTINCT (CONCAT_WS(',',tags.id,tags.displayName))) AS all_tags

我应该如何修改它?

有些人使用内部 (SELECT .. FROM) 但正如我听说的那样,它效率很低

Some people use an inner (SELECT .. FROM) but as I have heard, it is so inefficien

SELECT `posts`.*,`categories`.*,`creators`.*,`editors`.*
CONCAT_WS(';', DISTINCT GROUP_CONCAT(CONCAT_WS(',',tags.id,tags.displayName))) AS all_ids
FROM (`posts`) 
LEFT JOIN `languages` ON `posts`.`language_id`=`languages`.`id` 
LEFT JOIN `users` as creators ON `posts`.`creatorUser_id`=`creators`.`id` 
LEFT JOIN `users` as editors ON `posts`.`lastEditorUser_id`=`editors`.`id` 
LEFT JOIN `userProfiles` as editors_profile ON `editors`.`profile_id`=`editors_profile`.`id` 
LEFT JOIN `categories` ON `posts`.`category_id`=`categories`.`id` 
LEFT JOIN `postTags` ON `postTags`.`post_id`=`posts`.`id` 
LEFT JOIN `tags` ON `postTags`.`tag_id`=`tags`.`id` 
LEFT JOIN `postTags` as `nodetag_checks` ON `nodetag_checks`.`post_id`=`posts`.`id` 
LEFT JOIN `tags` as `tag_checks` ON `nodetag_checks`.`tag_id`=`tag_checks`.`id` 
WHERE ( 9 IN(`tag_checks`.`id`,`tag_checks`.`cached_parents`) OR 10 IN(`tag_checks`.`id`,`tag_checks`.`cached_parents`) OR 11 IN(`tag_checks`.`id`,`tag_checks`.`cached_parents`)) 
GROUP BY `posts`.`id` ORDER BY `posts`.`created` desc LIMIT 0, 20  

推荐答案

试试这个:

GROUP_CONCAT(
  DISTINCT CONCAT(tags.id,',',tags.displayName) 
  ORDER BY posts.id 
  SEPARATOR ';'
)

这篇关于mysql GROUP_CONCAT DISTINCT 多列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)
SQL/MySQL: split a quantity value into multiple rows by date(SQL/MySQL:按日期将数量值拆分为多行)