dow98764 2018-09-18 13:39
浏览 23
已采纳

Not()属于错误的表

I am using go version go1.10.3 linux/amd64 and mysql 5.7.

Need to runnable with GORM's docker compose config or please provides your config.

package main

import (
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/mssql"
    _ "github.com/jinzhu/gorm/dialects/mysql"
    _ "github.com/jinzhu/gorm/dialects/postgres"
    _ "github.com/jinzhu/gorm/dialects/sqlite"
)

var db *gorm.DB

func init() {
    var err error

     db, err = gorm.Open("mysql", "gorm:gorm@tcp(localhost:9910)/gorm?charset=utf8&parseTime=True")

    if err != nil {
        panic(err)
    }
    db.LogMode(true)
}

type Res {
    Id int  `gorm:"column:id"`
    age int  `gorm:"column:age"`
}

func main() {
        var result []Res
    db.Table("A").Select("A.id,A.age").Joins("left join B on A.id=B.id").
        Where("A.age=28").
       Not("B.id", []{2,3,4,5}).
       Scan(&result)
       fmt.Printf("%v", result)
}

The sql log is:

select A.id,A.age from A left join B on A.id=B.id where a.age=28 and A.B.id not in(2,3,4,5)

As can be seen, the not operation is appended for the table A (A.B.id not in ...). How can it be appended to table B (B.id not in ...)?

  • 写回答

2条回答 默认 最新

  • douchen1988 2018-09-18 16:47
    关注

    First off, as per my comment: You're only using mysql as a DB, and yet you're importing all the dialect packages (which do call their respective init functions. These functions register callbacks that are dialect-specific (e.g. the init func in the MsSQL package). Remove all the dialects you're not using from your imports:

    // remove lines that I've commented out here...
    import (
        "github.com/jinzhu/gorm"
        // _ "github.com/jinzhu/gorm/dialects/mssql"
         _ "github.com/jinzhu/gorm/dialects/mysql"
        // _ "github.com/jinzhu/gorm/dialects/postgres"
        // _ "github.com/jinzhu/gorm/dialects/sqlite"
    )
    

    You could move the NOT IN part of the WHERE clause to the JOIN condition based off of the documentation.

    I'd also check any errors that you may encounter, they might give you more debug information on top of the log:

    err := db.Table("A").Select("A.id,A.age").
        Joins("LEFT JOIN B on A.id =  B.id AND B.id NOT IN (?)", []int{2, 3, 4, 5}).
        Where("age = ?", 28).
        Scan(&result).Error
    if err != nil {
        fmt.Fatalf("Failed to execute query: %+v", err)
    }
    fmt.Prinln(result)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 目详情-五一模拟赛详情页
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line