有这样一个需求,先说下表结构,这个表里有帖子信息和问答信息,1对1或者1对多。type 1是帖子信息类型 2 是问答类型
CREATE TABLE `wenda` (
`id` int(11) NOT NULL AUTO_INCREMENT, `title` varchar(50) NOT NULL, `type` int(4) DEFAULT NULL, `tieziId` int(11) DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;
如何按照一个帖子,一个最新的问答,取出列表的数据
select tiezi.*,wenda.* from wenda as tiezi left join (select a.id,a.title,a.tieziId from wenda a where type = 2 and 1 > (select count(*) from wenda where type = 2 and tieziId=a.tieziId and id>a.id) order by a.tieziId,a.id desc) as wenda on tiezi.id = wenda.tieziId where tiezi.type = 1
当然不推荐这样设计表,只是针对这个表查询做一下说明罢了。
另外有更好的sql,欢迎讨论。
欢迎加入我的qq群:425783133
