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?
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?
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)
EDIT? Since you are saying you don't know anything other than this SQL, you could use raw SQL as such:
var field1 string
rows, err := db.Raw("SELECT A.field1 FROM tbl1 AS A inner join tbl2 AS B on A.field2=B.field2 where b.Field3 = ?", "something").Rows()
defer rows.Close()
for rows.Next() {
rows.Scan(&field1)
// ...
}
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
Models
type tbl1 struct {
field1 string
field2 string
}
type tbl2 struct {
field1 string
field2 string
}
SQL
SELECT A.field1 FROM tbl1 A INNER JOIN tbl2 B ON A.field2 = B.field2
Gorm
db.
Model(tbl1{}).
Select("A.field1").
Joins("INNER JOIN tbl2 B ON A.field2 = B.field2").
Scan(&tbl1{})