【发布时间】:2021-05-06 15:41:28
【问题描述】:
我想写一个类似的查询
SELECT table_a.*, table_c.*
FROM table_a
LEFT JOIN table_b ON table_a.id = table_b.table_a_id
LEFT JOIN table_c ON table_b.id = table_c.table_b_id
WHERE table_a.column_a = 'a_value',
AND table_c.column_b = 'some_value'
AND table_c.column_c = 'another_value';
编辑:我错过了非常重要的一点,即 where 子句变量不固定。根据输入,每个表可能使用更多或更少的列。
目前,我的查询看起来像
db.Table("table_a").
Joins("left join table_b on table_a.id = table_b.table_a_id").
Joins("left join table_c on table_b.id = table_c.table_b_id").
Select("table_a.*, table_c.*").
Table("table_a").Where(map[string]interface{}{"column_a": "value"}).
Table("table_c").Where(map[string]interface{}{
"column_b": "some_value",
"column_c": "another_value",
}).
Find(&elem)
但是,记录的 SQL 语句是
SELECT table_a.*, table_c.*
FROM `table_c` # gorm gives the wrong starting table, should be table_a
LEFT JOIN table_b ON table_a.id = table_b.table_a_id
LEFT JOIN table_c ON table_b.id = table_c.table_b_id
WHERE (`table_c`.`column_a` = 'value') # wrong table again
AND (`table_c`.`column_b` = 'some_value')
AND (`table_c`.`column_c` = 'another_value')
我不确定这里有什么问题。使用这种语法是否无法同时查询不同的表?我希望尽可能避免使用原始查询。
更新:我尝试过动态生成 SQL where 子句,但如果有 gorm 提供的更直接的方法,我会更喜欢。
【问题讨论】: