树状数据库表查询2次以上(自连接、内连接、别名)方法

时间:2022-07-24
本文章向大家介绍树状数据库表查询2次以上(自连接、内连接、别名)方法,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

https://blog.csdn.net/qq_15058425/article/details/78506193

https://blog.csdn.net/qq_43998763/article/details/103528559

https://blog.csdn.net/zhangt85/article/details/40544165

https://www.cnblogs.com/baiyuhong/p/9753173.html

对于树状结构的数据库表,如何在一个表中查询多次,开始走了不少弯路,比如想尝试用子查询,方向不对。其实就是join查询使用数据库表别名(改变数据表名称)即可。

//价值表带mark分值
type UserMeritTopic2 struct {
	// gorm.Model
	Id         int64  `json:"id"`
	Title      string `json:"title"`
	Title1     string `json:"title1"`     //价值分类名称
	Title2     string `json:"title2"`     //价值分类名称
	Title3     string `json:"title3"`     //价值分类名称
	TopicTitle string `json:"topictitle"` //价值内容名称
	Mark       int    `json:"mark"`
	Content    string `json:"content"`
	User       User
}

//测试查询,希望查询出树状结构表的父子孙
//最后用join查询重命名来解决了。
func GetMeritTopic2(mid, uid int64, state int) (usermerittopics []*UserMeritTopic2, err error) {
	db := GetDB()

	err = db.Table("admin_merit").Select("t2.title as title2,t1.title as title1,admin_merit.title as title,admin_merit_mark.mark as mark,merit_topic.title as topic_title,merit_topic.content as content").
		Where("admin_merit.parent_id=?", mid).
		Joins("INNER JOIN admin_merit AS t1 ON t1.id = admin_merit.parent_id").
		Joins("INNER JOIN admin_merit AS t2 ON t2.id = t1.parent_id").
		Joins("left JOIN merit_topic on merit_topic.merit_id=admin_merit.id").
		Where("merit_topic.user_id = ? AND merit_topic.state=?", uid, state).
		Joins("left JOIN admin_merit_mark on admin_merit_mark.merit_id = merit_topic.merit_id").
		Scan(&usermerittopics).Error
	return usermerittopics, err
}

gorm的查询结果如下: 

[
  {
    "id": 0,
    "title": "大型",
    "title1": "专业负责人",
    "title2": "项目管理类",
    "title3": "",
    "topictitle": "阿斯顿发生发送的",
    "mark": 4,
    "content": "阿斯蒂芬",
  }
]