Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a subquery in 'FROM' in gorm

Tags:

go

go-gorm

I would like to know how I can use a subquery in FROM clause using gorm. It would look like the following:

SELECT * FROM 
(
  SELECT foo.*
  FROM foo
  WHERE bar = "baz"
) AS t1
WHERE t1.id = 1;

I have built the subquery using golang:

db.Model(Foo{}).Where("bar = ?", "baz")

But how can I use this as a subquery in FROM?

If there is a method that turns a gorm query into a SQL string, then I can simply plug that string into a raw SQL. But there does not seem to be such method. Any suggestions?

like image 249
Sung Cho Avatar asked Oct 18 '17 10:10

Sung Cho


2 Answers

Also you can do it with join on a subquery

subQuery := db.
    Select("foo.*").
    Table("foo").
    Where("bar = ?", "baz").
    SubQuery()

db.
    Select("t1.*").
    Join("INNER JOIN ? AS t1 ON t1.id = foo.id", subQuery).
    Where("t1.id = ?", 1)
like image 130
Mykyta Nikitenko Avatar answered Oct 29 '22 11:10

Mykyta Nikitenko


You could use QueryExpr, refer

http://jinzhu.me/gorm/crud.html#subquery

db.Where("amount > ?", DB.Table("orders").Select("AVG(amount)").Where("state = ?", "paid").QueryExpr()).Find(&orders)

Which generate SQL

SELECT * FROM "orders" WHERE "orders"."deleted_at" IS NULL AND (amount > (SELECT AVG(amount) FROM "orders" WHERE (state = 'paid')));

like image 41
Jinzhu Avatar answered Oct 29 '22 12:10

Jinzhu