product
======================================================
id_______userid________title
1________a_____________xxxxx
2________a_____________xxxxx
3________a_____________xxxxx
4________b_____________xxxxx
5________b_____________xxxxx
6________b_____________xxxxx
7________c_____________xxxxx
8________c_____________xxxxx
9________c_____________xxxxx
10_______c_____________xxxxx
11_______d_____________xxxxx
=======================================================
要求:输出用户a、b、c的前3条记录。
现在我这样写:
(select * from product where userid='a' order by id limit 3)
union (select * from product where userid='b' order by id limit 3)
union (select * from product where userid='b' order by id limit 3)
...但当userid达到几十个时,这个查询效率极低。有什么查询能一次性输出要求的记录?

解决方案 »

  1.   

    select *
    from product p
    where 3>(select count(*) from product where userid=p.userid and id<p.id)
      

  2.   

    好强啊!
    每天看csdn只看MySql,
    每天看MYsql肯定看ACMAIN_CHM的回复。
      

  3.   

    select count(*) from product where userid=p.userid and id<p.id
    为什么要加后面得id<p.id呢,我不是很明白,希望得到版主的指点
      

  4.   

    这条语句构思不错,不过好像性能太差了。测试了在10个userid的情况下,比union慢了几十倍。
      

  5.   

    如果你的有索引 (userid,id ) 的话,你的UNION 应该效率高于一楼的语句。
    建议可以换成 union all