Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
703 views
in Technique[技术] by (71.8m points)

tags - mysql GROUP_CONCAT DISTINCT multiple columns

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

My query looks like:

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

This line causes problem:

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

How should I modify it?

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  
question from:https://stackoverflow.com/questions/18845170/mysql-group-concat-distinct-multiple-columns

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...