Home > Back-end >  Is this a valid SQL query
Is this a valid SQL query

Time:09-20

SELECT A.field1 FROM tbl1 AS A,tbl2 AS B WHERE A.field2=B.field2;

Or this the correct way

SELECT field1 FROM tbl1 AS A,tbl2 AS B WHERE A.field2=B.field2;

Assuming this is valid, how would you convert it into golang using gorm?

CodePudding user response:

Actually it depends. If field1 only exists in tbl1 or tbl2 then both would work. Otherwise first one is correct and removes ambiguity.

BTW, instead of using such old style inner join you should write that as:

SELECT A.field1 
FROM tbl1 AS A
inner join tbl2 AS B ON A.field2=B.field2;

With gorm:

db.Joins("Tbl2").Find(&tbl1)

CodePudding user response:

type Tbl1 struct {
....
}

var Fields []struct {
   Field1 string
}

-- gorm

err := gorm.Model(&Tbl1{}).
   Joins("tbl2 ON tbl1.field2 = tbl2.field2").
   Select("tbl1.field1").
   Scan(&Fields).Error
if err!=nil {
 ...
}

Reference: https://gorm.io/docs/query.html

  • Related