V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
yjsslab
V2EX  ›  问与答

急问个 sql问题?

  •  
  •   yjsslab · 2014-01-16 11:59:53 +08:00 · 2274 次点击
    这是一个创建于 3776 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    1970-01-01 08:00:00 +08:00
    manhere
        1
    manhere  
       2014-01-16 12:04:29 +08:00
    既然是一个,为什么还要用in() ?
    jandan
        2
    jandan  
       2014-01-16 12:07:06 +08:00
    多个结果是否一样?若是distinct。
    yjsslab
        3
    yjsslab  
    OP
       2014-01-16 12:08:24 +08:00
    @manhere 因为 in( .. 有很多个,一个一个可能慢点), 要是没办法,也只能一个一个来。
    因为 in 每一个都有多个结果
    yjsslab
        4
    yjsslab  
    OP
       2014-01-16 12:09:24 +08:00
    怎么不能改帖子了????
    yjsslab
        5
    yjsslab  
    OP
       2014-01-16 12:11:03 +08:00
    @manhere
    @jandan 形象一点:找一组帖子的最新那条评论。
    manhere
        6
    manhere  
       2014-01-16 12:14:20 +08:00
    @yjsslab 可以全读出来让程序处理排序
    yjsslab
        7
    yjsslab  
    OP
       2014-01-16 12:17:04 +08:00
    @manhere 就是因为这样太慢,相当于每个帖子有几百条评论,然后一次要查几十到百个帖子。
    clino
        8
    clino  
       2014-01-16 12:24:55 +08:00
    @yjsslab 给帖子增加一个最新评论的字段,每次有新评论就更新这个字段
    Maslino
        9
    Maslino  
       2014-01-16 12:27:56 +08:00
    @yjsslab 试试group by和子查询
    sun1991
        10
    sun1991  
       2014-01-16 12:56:54 +08:00
    如果是Oracle的话, 参见row_number, partition by
    http://www.java2s.com/Tutorial/Oracle/0320__Analytical-Functions/ROWNUMBERwithPartition.htm

    SQL Server应该有类似写法. 别的就不知道了
    ETiV
        11
    ETiV  
       2014-01-16 14:16:47 +08:00
    有自增序号(id)不?

    select MAX(t.id), t.a,t.b from t where t.c in (1, 2, 3, 4, 5) group by t.c;
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2096 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 05:32 · PVG 13:32 · LAX 22:32 · JFK 01:32
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.