magzza
V2EX  ›  数据库

向各位请教 sql 优化问题

  •  
  •   magzza · Apr 9, 2017 · 2256 views
    This topic created in 3325 days ago, the information mentioned may be changed or developed.
    select a.dept,a.cid,a.carno,(select top 1 gt+';'+x_baidu+';'+y_baidu+';'+st from gps b where b.cid = a.cid order by id desc ) conts from gps_car a

    gps_car 是车辆表, gps 表是 gps 表,367 万条数据.
    现在是想获取车辆表中每辆车在 gps 表中最新的一条 gps 信息。
    请教各人达人,我如上的 sql 语句要 20s 以上,该如何优化?
    5 replies    2017-04-10 12:53:06 +08:00
    incompatible
        1
    incompatible  
       Apr 9, 2017 via iPhone
    你这个需求还是从应用层面优化吧。
    建一个 latest_gps 表,存每辆车的最新一条的 gps 数据,车辆上报了最新的 gps 后更新此表。
    查询时 select from 此表不用加任何 where 条件即可。
    ivvei
        2
    ivvei  
       Apr 9, 2017
    不要把 select top 那句写到 外面这句的 select 部分。你放到后面去,做 join 都比现在这样强。

    说到, SQL 优化,先看执行计划。
    rqrq
        3
    rqrq  
       Apr 9, 2017
    select * from gps_car a inner join (select max(gps.自增字段), gps.cid from gps inner join gps_car on gps.cid = gps_car.cid group by gps.cid) b on a.cid = b.cid

    不过这样写, join 子查询用不了索引。
    ebony0319
        4
    ebony0319  
       Apr 9, 2017 via Android
    没有一个静态表记录最后的 gps 位置要搞死人的,不管怎么写都要去扫描那个表。
    mko0okmko0
        5
    mko0okmko0  
       Apr 10, 2017
    补充楼上大家的东西:
    建议 mongodb(ram db 一类)+传统资料库
    mongodb 存放最后位置,甚至还可以设计局部经纬度聚合,用于查询某区域有多少人,或区域热点,或快查此区域每个人的位置,
    传统资料库就一直存入每个人的位置,不做查询或是把查询设计到 mongodb 上.
    速度差的不是一个等级,是好几个等级 @@
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3040 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 63ms · UTC 09:00 · PVG 17:00 · LAX 02:00 · JFK 05:00
    ♥ Do have faith in what you're doing.