汗。 我不知道你的主表 跟帖表有什么字段 打个比方说 主题表有字段 id 跟帖表有字段 parentId你就select count(*) from 跟帖表 where 跟帖表.parentId=主题表.id and 主题表.id=XXX 不就行了 你dao类随便写个方法 像 int getXXXNum()封装一下这个jdbc操作,action调用就是了
DAO类写方法 int getXXXNum(String id)Action写点诸如String id = (String)request.getParameter("id"); XXXDao xxxDao = new XXXDao(); int num = xxxDao.getXXXNum(id); 或者你id从actionForm拿,都一样的
大哥,别走! 是这么个意思:在model类中,查询所有的主题,在Action中接受这个集合,但是呢,这只是主题表中的内容,像 统计 回帖数量,是可以用sql语句得到,问题是我怎么做?很困惑!
非得表关联么?
我不知道你的主表 跟帖表有什么字段
打个比方说
主题表有字段
id
跟帖表有字段
parentId你就select count(*) from 跟帖表 where 跟帖表.parentId=主题表.id and 主题表.id=XXX
不就行了
你dao类随便写个方法 像 int getXXXNum()封装一下这个jdbc操作,action调用就是了
大哥,跟贴表有一个字段用来判断是哪一个主题的,是 主题表的 id; 当然可以写个方法,action直接调用。 问题是,我查询 所有主题,返回一个 集合类,那么 我的这个getXXXNum()方法,需要知道主题的id,这个方法怎么写?
我怎么获得这个 id ?或者说 怎么 让这个 变量和 主题一一对应起来。 期待中。
XXXDao xxxDao = new XXXDao();
int num = xxxDao.getXXXNum(id);
或者你id从actionForm拿,都一样的
大哥,谢谢你! 我的这步操作,没有formbean, model(SubjectBean)类有两个方法
该类有主题表中的所有字段,封装起来
定义了个构造方法,用于对这些字段赋值。
1.public ArrayList getAllSubject()
该集合里面是SubjectBean的对象。
2.public int getCount(int id) 我在Action中直接调用 getAllSubject(),返回了ArrayList,但这只是主题表中的内容, 至于这个getCount方法,我应该在哪里调用,怎么去取得id值?如何使它和主题一一对应? 我比较笨,请赐教
很谢谢您的回复!我的数据库很简单,只是为了练Struts随便建的。
您说的是可以很好的解决这个问题。 我还有一个疑问:就是如果出现类似的情况,我应该怎么去解决?比如说 最后 回复人?
假如表中没有这个字段,应该怎么办?当你遇到这样的问题时,你是怎么解决的?请说说您的思路!
1.SQL语句连表查询
2.更改数据表设计,在“主题表”中增加冗余字段“跟帖数”
当跟帖表中有新数据插入时,同时更新主题表中的字段值。
查询的时候就相当方便。
--数据库脚本
create database if not exists `test`;USE `test`;/*Table structure for table `reply` */DROP TABLE IF EXISTS `reply`;
--回帖表
CREATE TABLE `reply` (
`id` bigint(20) NOT NULL auto_increment,
`pid` bigint(20) default NULL,
`content` text,
`user` varchar(20) default NULL,
`create` date default NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;/*Data for the table `reply` */insert into `reply` values (1,1,'哇哈哈','二毛','2007-11-27'),(2,1,'哈哈哇\r\n','三毛','2007-11-30');/*Table structure for table `theme` */DROP TABLE IF EXISTS `theme`;
--主题帖表
CREATE TABLE `theme` (
`id` bigint(20) NOT NULL auto_increment,
`title` varchar(255) default NULL,
`content` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;/*Data for the table `theme` */insert into `theme` values (1,'中国','哈哈哈 ');
--查询SQL
select t00.*,t01.r_count,t02.user from theme t00 join (select count(t1.id) as r_count,max(t2.id) as r_id,t1.id from theme t1 join reply t2 on t1.id=t2.pid group by t1.id) t01 on t00.id=t01.id
join reply t02 on t01.r_id=t02.id