英文:
Alias the main table's name in a Gorm query
问题
我有一个类似的 Gorm 查询:
db.
Table(fmt.Sprintf("%s t", model.BlogTag{}.TableName())).
Select(`
t.id,
t.path,
t.title,
t.hits,
COUNT(DISTINCT b.id) AS used_times
`).
Joins("LEFT JOIN contentitem_tag_map bt ON bt.tag_id = t.id").
Joins("LEFT JOIN content b ON b.id = bt.content_item_id AND b.state = 1").
Where("t.published = 1").
Group("t.id").
Order("used_times DESC").
Find(&tags).Error
生成的查询语句如下:
SELECT t.id, t.path, t.title, t.hits, COUNT(DISTINCT b.id) AS used_times
FROM `myschema`.`vk9wz_tags`
LEFT JOIN myschema.vk9wz_contentitem_tag_map bt ON bt.tag_id = t.id
LEFT JOIN myschema.vk9wz_content b ON b.id = bt.content_item_id AND b.state = 1
WHERE t.published = 1
GROUP BY `t`.`id`
ORDER BY used_times DESC
我尝试指定别名 t
,但 Gorm 没有识别到它!因此,MySQL 无法理解首先是什么意思的 t
。
据我所见,文档中没有说明如何指定表别名。
有没有办法在查询中避免使用完整的表名?
英文:
I have a Gorm query similar to:
db.
Table(fmt.Sprintf("%s t", model.BlogTag{}.TableName())).
Select(`
t.id,
t.path,
t.title,
t.hits,
COUNT(DISTINCT b.id) AS used_times
`).
Joins("LEFT JOIN contentitem_tag_map bt ON bt.tag_id = t.id").
Joins("LEFT JOIN content b ON b.id = bt.content_item_id AND b.state = 1").
Where("t.published = 1").
Group("t.id").
Order("used_times DESC").
Find(&tags).Error
The resulting query looks like:
SELECT t.id, t.path, t.title, t.hits, COUNT(DISTINCT b.id) AS used_times
FROM `myschema`.`vk9wz_tags`
LEFT JOIN myschema.vk9wz_contentitem_tag_map bt ON bt.tag_id = t.id
LEFT JOIN myschema.vk9wz_content b ON b.id = bt.content_item_id AND b.state = 1
WHERE t.published = 1
GROUP BY `t`.`id`
ORDER BY used_times DESC
The alias t
I tried to specify is not picked up by Gorm! Therefore MySQL doesn't understand what t
is in first place.
The documentation doesn't include how to specify the table alias, as far as I can see.
Is there any way I can avoid using the full name in my query?
答案1
得分: 4
尝试使用:
db.Table(model.BlogTag{}.TableName() + " AS t")
英文:
Try using:
db.Table(model.BlogTag{}.TableName() + " AS t")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论