有3个表 :m,t,sm表:
uid tid sid time.....t表
tid类别ID tname类别名称 ....s表:
sid物品ID tid物品所属类别 sname物品名称 .....我想查询出m表里uid=1的记录,同时查询出字段:g.gname,s.sname.将结果按照类别tid倒序分组,每组超过3条的只要按时间倒序前3条比如:
tid   tname  sid   sname    time
 9     t9     4     s4       00-00-10
 9     t9     9     s9       00-00-5
 9     t9     5     s5       00-00-3 6     t6     10    s10       00-00-10
 6     t6     14    s14       00-00-7 4     t4     17    s17       00-00-10
 4     t4     16    s16       00-00-7
 4     t4     18    s18       00-00-4

解决方案 »

  1.   

    select t1.tid,t.tname,s.sid,s.sname,t1.time
    from m t1 left join t
    on t1.tid=t.id
    left join s
    on t1.sid=s.id 
    where t1.uid=1 and 3>(select count(*) from m where tid=t1.tid and time>t1.time)
    order by t1.tid desc,t1.time desc;
      

  2.   

    select t2.tid, t3.tname, t2.sid, t4.sname, t2.`time`
    from
    (
    select t1.*,(select count(1)+1 from m表 
      where uid=1 and tid=t1.tid and `time`>t1.`time`) as order_number 
    from m表 t1
    where t1.uid=1
    ) t2, t表 t3, s表 t4
    where t2.tid=t3.tid and t2.sid=t4.sid and t2.order_number<=3
      order by t2.tid desc,t2.order_number;