mysql:不要忽略重复匹配

igetnqfo  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(372)

我有以下数据库:

CREATE DATABASE `mytest`;

USE `mytest`;

CREATE TABLE `TestTable` (
  `TestID` int(11) NOT NULL AUTO_INCREMENT,
  `TestValue` varchar(256) NOT NULL,
  PRIMARY KEY (`TestID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=COMPRESSED;

INSERT INTO `TestTable` VALUES (1,'Example1'),(2,'Example2'),(3,'Example3'),(4,'Example4');

我想在这样的表上执行一个查询,在这里我可以找到所有匹配项(甚至是重复的匹配项)。也就是说,假设我想获得与id(1,2,1)相关的行,我想获得:

+---------------------------------------+
| GROUP_CONCAT(TestValue SEPARATOR '|') |
+---------------------------------------+
| Example1|Example2|Example1            |
+---------------------------------------+

然而,这就是我能做到的:

mysql> select GROUP_CONCAT(TestValue SEPARATOR '|') from TestTable where TestID IN (1,2,1);
+---------------------------------------+
| GROUP_CONCAT(TestValue SEPARATOR '|') |
+---------------------------------------+
| Example1|Example2                     |
+---------------------------------------+
1 row in set (0,00 sec)

有什么办法吗?

ddarikpa

ddarikpa1#

使用派生表和 left join :

select GROUP_CONCAT(t.TestValue SEPARATOR '|')
from (select 1 as testid union all select 2 union all select 1) i left join
     TestTable t
     using (TestID);

如果要保留排序,则可以包括:

select GROUP_CONCAT(t.TestValue ORDER BY i.ord SEPARATOR '|')
from (select 1 as ord, 1 as testid union all
      select 2, 2 union all
      select 3, 1
     ) i left join
     TestTable t
     using (TestID);

相关问题