LoginSignup
1
0

More than 1 year has passed since last update.

[GORM]複合主キーによるDeleteのSQL文

Posted at

GORMDelete()のSQL文が、複合主キーの場合に、少しイレギュラーであったため、書き留めました。

  • 環境
go 1.17
mysql 5.7

gorm.io/gorm v1.22.0 ( GORM自体のv2に当たる。v1は、jinzhu/gormの方 )
gorm.io/driver/mysql v1.1.2

以下のような複合主キーのテーブルの場合に、

type Item struct {
	Pk1  string `gorm:"primaryKey;autoIncrement:false;"`
	Pk2  string `gorm:"primaryKey;autoIncrement:false;"`
	Name string
}

GORMのDelete()を使うと、

item := Item{
		Pk1:  "test1",
		Pk2:  "test2",
		Name: "name",
}
db.Delete(&item)

IN句を使ったSQL文になります。

DELETE FROM `item` WHERE (`item`.`pk1`,`item`.`pk2`) IN (('test1','test2'));

この場合、pk1,pk2のインデックスが効かなくなることがあるので注意が必要です。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0