--
-- 表的结构 `test`
--CREATE TABLE IF NOT EXISTS `test` (
`id` int(10) NOT NULL auto_increment,
`class` varchar(20) collate utf8_unicode_ci NOT NULL,
`name` varchar(50) collate utf8_unicode_ci NOT NULL,
`age` varchar(100) collate utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=10 ;--
-- 导出表中的数据 `test`
--INSERT INTO `test` (`id`, `class`, `name`, `age`) VALUES
(1, 'A', 'aaa', '20'),
(2, 'A', 'bbb', '25'),
(3, 'B', 'ddd', '30'),
(4, 'C', 'sss', '40'),
(5, 'B', 'sssffff', '50'),
(6, 'A', 'rrr', '33'),
(7, 'A', 'eee', '15'),
(8, 'B', 'www', '55'),
(9, 'C', 'hhh', '22');现在我想在数据库中,或者输出的时候在表格中显示下面的效果,相同的class合并在一行。班级 姓名 年龄 人数
A aaa 20 4
bbb 25
rrr 33
eee 15
B ddd 30 3
sssffff 50
www 55
C sss 40 2
hhh 22
在数据库中如何实现?在页面的表格中又怎么实现?
-- 表的结构 `test`
--CREATE TABLE IF NOT EXISTS `test` (
`id` int(10) NOT NULL auto_increment,
`class` varchar(20) collate utf8_unicode_ci NOT NULL,
`name` varchar(50) collate utf8_unicode_ci NOT NULL,
`age` varchar(100) collate utf8_unicode_ci NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=10 ;--
-- 导出表中的数据 `test`
--INSERT INTO `test` (`id`, `class`, `name`, `age`) VALUES
(1, 'A', 'aaa', '20'),
(2, 'A', 'bbb', '25'),
(3, 'B', 'ddd', '30'),
(4, 'C', 'sss', '40'),
(5, 'B', 'sssffff', '50'),
(6, 'A', 'rrr', '33'),
(7, 'A', 'eee', '15'),
(8, 'B', 'www', '55'),
(9, 'C', 'hhh', '22');现在我想在数据库中,或者输出的时候在表格中显示下面的效果,相同的class合并在一行。班级 姓名 年龄 人数
A aaa 20 4
bbb 25
rrr 33
eee 15
B ddd 30 3
sssffff 50
www 55
C sss 40 2
hhh 22
在数据库中如何实现?在页面的表格中又怎么实现?
这个帖子不就是你问的吗?问的问题也都一样
你是说对于同一类的只在第一条记录显示“班级”和“人数”,则只能通过程序控制了
可以用:
select a.class,name,age,a.c from test,(select count(*) c,class from test group by class) a where a.class=test.class order by class;
显示结果集,然后用程序对结果集显示成你所要的模式
case when exists(select 1 from test where class=a.class and id<a.id) then '' else a.class end as `班级`,
a.name as `姓名`,
a.age as `年龄`,
case when exists(select 1 from test where class=a.class and id<a.id) then '' else ltrim(b.cnt) end as `人数`
from
test a,
(select class,count(1) as cnt from test group by class) b
where
a.class=b.class
order by
a.class,
a.id
班级 姓名 年龄 人数
A aaa 20 4
bbb 25
rrr 33
eee 15
B ddd 30 3
sssffff 50
www 55
C sss 40 2
hhh 22
**/