表t1
字段
c1 id
c2 subject
c3 img
模拟数据如下
id subject img
1  s1      1.gif
1  s1      2.gif
1  s1      3.jpg
5  ssss8   yy.gif
5  ssss8   uu2.jpg
5  ssss8   sh.png
8  yy      77.gif
8  yy      99.jpgid与subject一一对应。但是一个可能对应多个img
现在求一条sql语句,
取出表中所有最新的img,但是一个id只要一个img(最后一个img,如果能每次查询都随机挑一个img更好)
并倒序排序查询结果类似
8  yy     99.jpg
5  ssss8  sh.png
1  s1     3.jpg

解决方案 »

  1.   

    加入自增ID
    SELECT A.* FROM T1 A WHERE NOT EXISTS(SELECT 1 FROM T1 WHERE A.id=id AND A.subject=subject
    AND A.ID<ID)
      

  2.   

    select pa.aid,pt.tid,pt.fid,pt.subject,pa.attachurl from pw_threads pt ,pw_attachs pa,pw_forums pf where pt.tid = pa.tid and pt.fid = pf.fid and pa.type='img' and pt.ifcheck='1' and (pf.f_type = 'forum' or pf.f_type = 'former') and pf.password = '' and (pt.topped>0 or pt.digest>0 or pt.if=1) order by pt.postdate desc limit实际的查询就是个连表查询,aid就是你要得自增列。
    tid就是id,与subject一一对应。
    attaurl就是img
    请问如何写这个查询
    现有的查询只能列出倒序列出attchchurl,不能按每个tid列出一个attchurl
      

  3.   


    select id,subject,img
    from tb
    group by id,subject
      

  4.   

    获益匪浅,
    select pa.aid,pt.tid,pt.fid,pt.subject,pa.attachurl from pw_threads pt ,pw_attachs pa,pw_forums pf where pt.tid = pa.tid and pt.fid = pf.fid and pa.type='img' and pt.ifcheck='1' and (pf.f_type = 'forum' or pf.f_type = 'former') and pf.password = '' and (pt.topped>0 or pt.digest>0 or pt.if=1) order by pt.postdate desc limit实际的查询就是个连表查询,aid就是你要得自增列。
    tid就是id,与subject一一对应。
    attaurl就是img
    请问如何写这个查询
    现有的查询只能列出倒序列出attchchurl,不能按每个tid列出一个attchurl要是能直接把这个改成我需要的就更好了,语句稍微复杂了一点,所以我很难按你们的提示修改。
    再加20分
      

  5.   

    根据楼的代码修改,将T1修改为你的查询代码,OR 将查询存为VIEW
      

  6.   


    你的这个语句中有小写id和大写ID表示不同的东西吧。
    按我看好像小些id表示tid,而大写ID表示aid,但是subject在pw_threads表里,不在pw_attchs表里,
    按你的写法,我还不会改。
      

  7.   


    我按你的提示改成了
    select aid,tid,attachurl from pw_attachs group by tid
    可以查询,但是没法融合到我原来的连表查询当中。
    还有就是最好能随机取到attachurl
      

  8.   

    select pa.aid,pt.tid,pt.fid,pt.subject,pa.attachurl from pw_threads pt,(select aid,tid,attachurl from pw_attachs group by tid) pa,pw_forums pf where pt.tid = pa.tid and pt.fid = pf.fid and pa.type='img' and pt.ifcheck='1' and (pf.f_type = 'forum' or pf.f_type = 'former') and pf.password = '' and (pt.topped>0 or pt.digest>0 or pt.if=1) order by pt.postdate desc limit 0,10改成这样,不行,语法错误啦