当前位置:   article > 正文

mysql GROUP_CONCAT 以及 其逆过程_groupconcat的逆操作

groupconcat的逆操作

新建多选选项表types 以及 选择结果表 user_MultiSelect

  1. DROP TABLE IF EXISTS `types`;
  2. CREATE TABLE `types` (
  3. `id` int(11) NOT NULL AUTO_INCREMENT,
  4. `types` smallint(6) NOT NULL,
  5. `comment` varchar(10) NOT NULL,
  6. PRIMARY KEY (`id`)
  7. ) ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8;
  8. /*Data for the table `types` */
  9. insert into `types`(`id`,`types`,`comment`) values
  10. (1,1,'a'),
  11. (2,2,'b'),
  12. (3,3,'c'),
  13. (4,4,'d'),
  14. (5,5,'e'),
  15. (6,6,'f'),
  16. (7,7,'g'),
  17. (8,8,'h'),
  18. (9,9,'i'),
  19. (10,10,'j');
  20. /*Table structure for table `user_MultiSelect` */
  21. DROP TABLE IF EXISTS `user_MultiSelect`;
  22. CREATE TABLE `user_MultiSelect` (
  23. `id` int(11) NOT NULL AUTO_INCREMENT,
  24. `userId` int(11) NOT NULL,
  25. `multiSelect` varchar(20) NOT NULL,
  26. PRIMARY KEY (`id`)
  27. ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
  28. /*Data for the table `user_MultiSelect` */
  29. insert into `user_MultiSelect`(`id`,`userId`,`multiSelect`) values
  30. (1,1,'1,2,3,'),
  31. (2,2,'2,'),
  32. (3,3,'5,6,7,'),
  33. (4,7,'4,5'),
  34. (5,9,'8,9,'),
  35. (6,11,'10');

一个多选结果分拆成多行单选comment

  1. SELECT b.id,a.`types`,a.comment,b.multiSelect
  2. FROM `types` a LEFT JOIN `user_MultiSelect` b ON LOCATE(a.types,b.multiSelect)>0

一个多选结果对应其相应的多选comment

  1. SELECT b.id,GROUP_CONCAT(a.comment),b.multiSelect
  2. FROM `types` a LEFT JOIN `user_MultiSelect` b ON LOCATE(a.types,b.multiSelect)>0
  3. GROUP BY b.id;

问题反思:当选项个数超过10 , LOCATE(a.types,b.multiSelect)>0会将1,10+ 同时查询到,使用的时候 请添加相应的限制条件

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/75018
推荐阅读
相关标签
  

闽ICP备14008679号