How to do union of multiple tables with where clause and order by in GORM (golang)

huangapple go评论71阅读模式
英文:

How to do union of multiple tables with where clause and order by in GORM (golang)

问题

我正在尝试对多个表进行联合操作,选择特定的列,并在结果集上运行where子句和order by子句。我该如何在GORM(Golang)中编写这个操作?

我尝试了以下代码片段,但是在数据库查询中没有运行where子句和order by子句:

var union []map[string]interface{}
database.CONNECTION.Raw("? UNION ?",
	database.CONNECTION.Select(ContentAttributes).Model(&model1{}),
	database.CONNECTION.Select(ContentAttributes).Model(&model2{}),
).Where("id > ?", 1).Order("Name").Scan(&union)

注意:ContentAttributes是一个包含我想要选择的属性的字符串切片。

它运行了以下查询:

SELECT "id","name","created_at","updated_at" FROM "model1" WHERE "model1"."deleted_at" IS NULL UNION SELECT "id","name","created_at","updated_at" FROM "model2" WHERE "model2"."deleted_at" IS NULL

我期望它在联合结果集上运行where条件和order by子句。但它只是执行了联合操作,并将结果收集到union变量中。请建议一种方法来实现这个需求。

英文:

I'm trying to do union of multiple tables with selected columns and run where clause and order by clause on the resultset. How do I write this in GORM (Golang)

I tried the following snippet, but didn't run the where clause and order by clause in the DB query:

var union []map[string]interface{}
database.CONNECTION.Raw("? UNION ?",
	database.CONNECTION.Select(ContentAttributes).Model(&model1{}),
	database.CONNECTION.Select(ContentAttributes).Model(&model2{}),
).Where("id > ?", 1).Order("Name").Scan(&union)

N.B. ContentAttributes is a slice of string which contains the attributes I want to select.

It's running the following query:

SELECT "id","name","created_at","updated_at" FROM "model1" WHERE "model1"."deleted_at" IS NULL UNION SELECT "id","name","created_at","updated_at" FROM "model2" WHERE "model2"."deleted_at" IS NULL

I expected this to run the where condition and the order by clause on the union resultset. But it just did union and collected the results in the union variable. Please suggest a way to do this.

答案1

得分: 1

不确定这是否是最简洁的方法,但它可以工作。

var db = database.CONNECTION
var union []map[string]interface{}
var raw = "SELECT * (? UNION ?) union WHERE union.id > ? ORDER BY union.name"

db.Raw(raw,
    db.Select("*").Model(&model1{}),
    db.Select("*").Model(&model2{}),
    1
).Scan(&union) 
英文:

Not sure if this is the cleanest way to do it but it works.

var db = database.CONNECTION
var union []map[string]interface{}
var raw = "SELECT * (? UNION ?) union WHERE union.id > ? ORDER BY union.name"

db.Raw(raw,
    db.Select("*").Model(&model1{}),
    db.Select("*").Model(&model2{}),
    1
).Scan(&union) 

huangapple
  • 本文由 发表于 2022年6月24日 15:47:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/72740629.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定