GORM 'NOT IN' 子查询

SNr*_*NrS 3 go go-gorm

我想执行一个子查询,例如:

 SELECT id, col1, col2 FROM table1 WHERE col1='val1' and col2 NOT IN (
  SELECT ID FROM table2 WHERE col1='val1' and col3 = 'val3')
Run Code Online (Sandbox Code Playgroud)

我如何使用GORM来执行它?

noa*_*amt 5

GORM可以编写查询。

编写一个标准查询,然后调用该.SubQuery()方法:

sub := db.Table("table2").Select("ID").Where("col1 = ?", 'val1').SubQuery()
Run Code Online (Sandbox Code Playgroud)

您可以将其作为参数放置在.Where()方法中

err := db.Table("table1").Where("col2 NOT IN ?", sub).Find(&table1Type).Error
//handle the error
Run Code Online (Sandbox Code Playgroud)