golang mysql多表查询_15.22数据库(22):MySQL多表联合查询

备注:所有查询基于前面章节中建立的中国数据库

```

/*联合查询*/

-- union

(select CityID,CityName from t_city where CityID between 6 and 10)

union

(select ProName,ProID from t_province where ProID between 6 and 10);

--查询中国共有多少地级市

select count(*) from t_city;

--查询河北省有多少地级市

select count(*) from t_city where ProID = (

select ProID from t_province where ProName = '河北省'

);

--统计各省地级市的数量

select ProID,count(CityID) from t_city

group by ProID;

--求每个省份中最大的城市ID

select ProID,max(CityID) from t_city

group by ProID;

--地级市最多的省份取前10名

select ProID,count(CityID) as cityCount from t_city

group by ProID

order by cityCount desc

limit 10;

--查询拥有区县最多的城市的前10名

select CityID,count(Id) as disCount from t_district

group by CityID

orde

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用Golang的gorm库进行递归查询的示例代码: ```go package main import ( "fmt" "gorm.io/driver/mysql" "gorm.io/gorm" ) type Category struct { ID uint Name string ParentID uint Children []Category `gorm:"foreignKey:ParentID"` } func main() { // 连接MySQL数据库 dsn := "user:password@tcp(127.0.0.1:3306)/database?charset=utf8mb4&parseTime=True&loc=Local" db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { panic(err) } // 自动迁移模式,创建categories db.AutoMigrate(&Category{}) // 创建分类数据 db.Create(&Category{Name: "电子产品"}) db.Create(&Category{Name: "手机", ParentID: 1}) db.Create(&Category{Name: "电脑", ParentID: 1}) db.Create(&Category{Name: "笔记本电脑", ParentID: 3}) db.Create(&Category{Name: "台式电脑", ParentID: 3}) db.Create(&Category{Name: "家具"}) db.Create(&Category{Name: "沙发", ParentID: 7}) db.Create(&Category{Name: "床", ParentID: 7}) // 递归查询分类数据 var categories []Category db.Preload("Children").Where("parent_id = ?", 0).Find(&categories) printCategories(categories, 0) } func printCategories(categories []Category, level int) { for _, category := range categories { fmt.Printf("%s%d. %s\n", getIndent(level), category.ID, category.Name) printCategories(category.Children, level+1) } } func getIndent(level int) string { var indent string for i := 0; i < level; i++ { indent += " " } return indent } ``` 上述代码中,我们定义了一个Category结构体,其中包含ID、Name、ParentID和Children四个字段。其中,ParentID示当前分类的父分类ID,Children示当前分类的子分类列。在查询时,我们使用Preload方法预加载Children字段,以便在查询结果中包含子分类数据。然后,我们使用Where方法指定ParentID为0,即查询所有顶级分类数据。最后,我们使用printCategories函数递归打印分类数据,其中getIndent函数用于生成缩进字符串,以便在输出时区分不同层级的分类。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值