如何与Gorm(Golang)中的Where子句和顺序进行多个表的联合

发布于 2025-02-10 01:06:00 字数 800 浏览 2 评论 0原文

我正在尝试与选定的列进行多个表进行联合,并在结果集的子句中运行子句和顺序。我如何在gorm(golang)中写这件

,我尝试了以下片段,但没有运行db查询中的从句和订单:

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)

nb content> content attributes是字符串的切片,其中包含该字符串我要选择的属性。

它正在运行以下查询:

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

我希望这将在联合结果集中运行在哪里条件和订单子句。但是它只是联合并在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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

对你而言 2025-02-17 01:06:00

不确定这是否是最干净的方法,但它起作用。

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) 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文