如何在 Gorm 的 where 语句中使用子查询?

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

How to do subquery on where statement with Gorm?

问题

我在使用gorm时遇到了一个小问题,当我需要在where语句中进行子查询时。我可以使用Raw方法轻松实现这一点,但我想使用gorm的方法,这样我的函数可以动态地进行更新。

我有一个更新查询,类似于这样:

UPDATE table_A 
SET
    col_A = ?,
    col_B = ?
WHERE col_C = 
(
    SELECT col_C from table_B 
    WHERE col_D = ?
)

以下是我使用最新的Gorm进行查询的代码,其中data是表A的结构体:

tx.Table("table_A").
Where("col_C", tx.Table("table_B").Select("col_C").Where("col_D", value_D)).
Updates(data)

然而,这个查询的结果是错误的,因为where子查询中的SELECT语句没有写在括号内:

UPDATE `table_A` SET `col_a`='col_A',`col_b`='col_B' WHERE col_C = SELECT col_C FROM `table_B` WHERE col_D = 'test123'

是否有办法使用gorm解决我的问题?或者目前gorm还不支持这个功能?

英文:

I got a little problem with gorm when I need to do subquery inside where statement. I can do this easily with Raw method, but I want to use gorm's method so my function can do this update dynamically.
I have query for update like this

	UPDATE table_A 
	SET
		col_A = ?,
		col_B = ?
	WHERE col_C = 
	(
		SELECT col_C from table_B 
		WHERE col_D = ?
	)

And here is my Query using newest Gorm where data inside Updates method is a struct of table A

tx.Table("table_A").
Where("col_C", tx.Table("table_B").Select("col_C").Where("col_D", value_D)).
Updates(data)

And this is the result, this result becomes an error because SELECT on where statement as subquery doesn't written inside parenthesis

UPDATE `table_A` SET `col_a`='col_A',`col_b`='col_B' WHERE col_C = SELECT col_C FROM `table_B` WHERE col_D = 'test123'

is there a way to solve my problem using gorm? or currently gorm still does not support it?

答案1

得分: 2

根据gorm文档,如果你传递一个*gorm.DB实例,gorm将能够执行子查询,但在我的情况下没有成功:)。所以我手动在子查询周围加上了括号,就像你的情况下这样做:

subquery := tx.Table("table_B").Select("col_C").Where("col_D", value_D)

tx.Table("table_A").
    Where("col_C = (?)", subquery).
    Updates(data)
英文:

Based in the gorm documentations, if you pass an instance of *gorm.DB, gorm will be able to perform the subquery, but in my case it didn't :). So what I did was I manually surrounded the subquery in parenthesis, something like this in your case:

subquery := tx.Table("table_B").Select("col_C").Where("col_D", value_D)

tx.Table("table_A").
    Where("col_C = (?)", subquery).
    Updates(data)

huangapple
  • 本文由 发表于 2022年8月2日 22:54:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/73209642.html
匿名

发表评论

匿名网友

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

确定