我有以下数据库:
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');
我想在这样的表上执行一个查询,其中我可以连接所有的匹配项(甚至是重复的)。 也就是说,假设我想获得与IDs(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)
有什么办法可以做到这一点吗?
使用派生表和左联接
:
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);