Using a subquery in 'FROM' in gorm

倾然丶 夕夏残阳落幕 提交于 2020-07-17 08:43:25

问题


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?


回答1:


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')));




回答2:


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)



回答3:


Author didn't use any "JOIN" in his SQL.

I didn't find any ORM way, but db.Raw works.

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

db.Raw("SELECT * FROM ? as t1 WHERE t1.id=?", subQuery, 1).Find(&rows)



回答4:


FYI – Jinzhu's method doesn't work

I have subqueries working using this method...

var somevalue = 1
row := db.Select("something").Table("first_table").Where("exists(?)", db.Select("a_relationship_to_something").Model(&SecondTable{}).Where("id = ?", somevalue).QueryExpr()).Row()
var result string
row.Scan(&result)

I've tested this with row(), rows(), first(), and find(). You can also use both .Table() and .Model() interchangeably as shown in the example.




回答5:


also could be used in join

subQuery:=db.Find(&subTable).QueryExpr()

db.
Table("table").
Select("*").
Join("join (?) as t1 on t1.id==table.id", //<---round brackets for multiple rows
subQuery).
Find(&Rows)




回答6:


Solved this issue by creating a package for more flexibility: https://github.com/loeffel-io/sql

subquery := sql.Create().
    Select(true, "purchases.*").
    Select(true, "...").
    From(true, "purchases").
    Join(true, "transactions ON transactions.purchase_id=purchases.id")

query := sql.Create().Select(true, "*").
    From(true, "(?) purchases", gorm.Expr(subquery.GetSQL(), subquery.GetValues()...)).
    Join(true, "transactions ON transactions.id=purchases.last_transaction_id")

db.
    Raw(query.GetSQL(), query.GetValues()...).
    Offset(...).
    Limit(...).
    Order(...).
    Unscoped().
    Find(&purchases).
    Error


来源:https://stackoverflow.com/questions/46807891/using-a-subquery-in-from-in-gorm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!