V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
yjsslab
V2EX  ›  问与答

急问个 sql问题?

  •  
  •   yjsslab · Jan 16, 2014 · 2922 views
    This topic created in 4493 days ago, the information mentioned may be changed or developed.
    select t.a,t.b from t where t.c in (1, 2, 3, 4, 5) order by created_at desc;
    怎么让每个 c 只返回一个结果?即最新created_at desc那个.
    如果直接这样:
    select t.a,t.b from t where t.c in (1, 2, 3, 4, 5) order by created_at desc limit 1;
    就全部一个结果.

    因为 select t.a,t.b from t where t.c = 1/2/3/4/5 每个都会返回多个结果
    11 replies    1970-01-01 08:00:00 +08:00
    manhere
        1
    manhere  
       Jan 16, 2014
    既然是一个,为什么还要用in() ?
    jandan
        2
    jandan  
       Jan 16, 2014
    多个结果是否一样?若是distinct。
    yjsslab
        3
    yjsslab  
    OP
       Jan 16, 2014
    @manhere 因为 in( .. 有很多个,一个一个可能慢点), 要是没办法,也只能一个一个来。
    因为 in 每一个都有多个结果
    yjsslab
        4
    yjsslab  
    OP
       Jan 16, 2014
    怎么不能改帖子了????
    yjsslab
        5
    yjsslab  
    OP
       Jan 16, 2014
    @manhere
    @jandan 形象一点:找一组帖子的最新那条评论。
    manhere
        6
    manhere  
       Jan 16, 2014
    @yjsslab 可以全读出来让程序处理排序
    yjsslab
        7
    yjsslab  
    OP
       Jan 16, 2014
    @manhere 就是因为这样太慢,相当于每个帖子有几百条评论,然后一次要查几十到百个帖子。
    clino
        8
    clino  
       Jan 16, 2014
    @yjsslab 给帖子增加一个最新评论的字段,每次有新评论就更新这个字段
    Maslino
        9
    Maslino  
       Jan 16, 2014
    @yjsslab 试试group by和子查询
    sun1991
        10
    sun1991  
       Jan 16, 2014
    如果是Oracle的话, 参见row_number, partition by
    http://www.java2s.com/Tutorial/Oracle/0320__Analytical-Functions/ROWNUMBERwithPartition.htm

    SQL Server应该有类似写法. 别的就不知道了
    ETiV
        11
    ETiV  
       Jan 16, 2014
    有自增序号(id)不?

    select MAX(t.id), t.a,t.b from t where t.c in (1, 2, 3, 4, 5) group by t.c;
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   6057 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 45ms · UTC 01:46 · PVG 09:46 · LAX 18:46 · JFK 21:46
    ♥ Do have faith in what you're doing.