如何在Go中提高MySQL查询的效率?

时间:2017-10-16 14:07:39

标签: mysql database go

我正在Go中编写一个API(我第一次使用该语言)并且我在循环中有一些MySQL查询。当它在较大的查询上运行时,它可能需要超过7-10秒的时间来回复并经常超时。有没有办法让这些查询更有效率?这只是数据库结构的问题,还是更简单的服务器规范?

Server spec是一款便宜的单核VPS,512MB RAM。

查询代码:

//Vendor search
reply, err: = db.Query("SELECT * FROM manuf_ids WHERE id='" + manuf + "';")
if err != nil {
    panic(err.Error())
}

for reply.Next() {
    var manufacturer Manufacturer
    err = reply.Scan( & manufacturer.ID, & manufacturer.Desc)
    if err != nil {
        panic(err.Error())
    }

    replytwo, err: = db.Query("SELECT id,descrip FROM dev_ids WHERE manuf='" + manuf + "';")
    if err != nil {
        panic(err.Error())
    }

    for replytwo.Next() {
        var devices Device
        err = replytwo.Scan( & devices.ID, & devices.Desc)
        if err != nil {
            panic(err.Error())
        }

        //Get sub-devices
        replythree, err: = db.Query("SELECT id,descrip FROM sub_dev_ids WHERE parent='" + devices.ID + "';")
        if err != nil {
            panic(err.Error())
        }

        for replythree.Next() {
            var sub_devices Sub
            err = replythree.Scan( & sub_devices.ID, & sub_devices.Desc)
            if err != nil {
                panic(err.Error())
            }
            devices.Subs = append(devices.Subs, sub_devices)
        }
        replythree.Close()
        manufacturer.Devs = append(manufacturer.Devs, devices)
    }
    replytwo.Close()
    results = append(results, manufacturer)
}
reply.Close()

我已经阅读了一些关于准备查询的内容,我在另一个函数中使用它来写入数据库,但我不确定这是否有用。我确实从循环中移除了我的延迟,这有所帮助,但是很少。

0 个答案:

没有答案