【问题标题】:Alias the main table's name in a Gorm query在 Gorm 查询中为主表的名称起别名
【发布时间】:2021-11-24 07:13:17
【问题描述】:

我有一个类似于以下的 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 首先是什么。

据我所知,文档不包括如何指定表别名。

有什么方法可以避免在查询中使用全名?

【问题讨论】:

标签: mysql go go-gorm


【解决方案1】:

尝试使用在我的项目中运行良好的 db.Table("?AS t", model.BlogTag{}.TableName())。

【讨论】:

  • 您介意解释一下您的答案吗?
  • 我很确定问题表函数中只是缺少“AS”来将表名与别名联系起来,此外没有必要使用 sprintf。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-13
  • 1970-01-01
  • 1970-01-01
  • 2021-03-20
  • 1970-01-01
相关资源
最近更新 更多