用MySQL GROUP BY按组列出所有行?
要按组列出所有行,可以使用GROUP_CONCAT()。让我们首先创建一个表-
create table DemoTable(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
Name varchar(20),
Value varchar(100)
);
使用插入命令在表中插入一些记录-
insert into DemoTable(Name,Value) values('John','John');insert into DemoTable(Name,Value) values('Carol','Carol');
insert into DemoTable(Name,Value) values('John','Works');
insert into DemoTable(Name,Value) values('Carol','Works');
insert into DemoTable(Name,Value) values('John','At');
insert into DemoTable(Name,Value) values('Carol','At');
insert into DemoTable(Name,Value) values('John','Amazon');
insert into DemoTable(Name,Value) values('Carol','Google');
使用select语句显示表中的所有记录-
select *from DemoTable;
这将产生以下输出-
+----+-------+--------+| Id | Name | Value |
+----+-------+--------+
| 1 | John | John |
| 2 | Carol | Carol |
| 3 | John | Works |
| 4 | Carol | Works |
| 5 | John | At |
| 6 | Carol | At |
| 7 | John | Amazon |
| 8 | Carol | Google |
+----+-------+--------+
8 rows in set (0.00 sec)
以下是按组列出所有行的查询。在这里,将获取“ John”的值,即“ John在id,3、5、7的Amazon工作。”同样,它也适用于“ Carol”-
select Name, GROUP_CONCAT(Value SEPARATOR ' ') AS `Complete_Status` from DemoTable group by Name;
这将产生以下输出-
+-------+-----------------------+| Name | Complete_Status |
+-------+-----------------------+
| Carol | Carol Works At Google |
| John | John Works At Amazon |
+-------+-----------------------+
2 rows in set (0.00 sec)
以上是 用MySQL GROUP BY按组列出所有行? 的全部内容, 来源链接: utcz.com/z/322502.html