当前位置:网站首页>11-grom-v2-04-advanced query
11-grom-v2-04-advanced query
2022-07-03 20:08:00 【Operation and maintenance xuandegong】
List of articles
1. use Struct or Map receive data
1.1 Find To Struct
Define a small structure to receive the query results in the table
db.Model(User{
}).Find(&UserModels)
- Complete example
Existing data sheet
mysql> select * from users;
+----+----------+------+--------------------+
| id | name | age | email |
+----+----------+------+--------------------+
| 1 | LiuBei | 28 | liubei@xishu.com |
| 2 | GuanYu | 22 | guanyu@xishu.com |
| 3 | ZhangFei | 20 | zhangfei@xishu.com |
+----+----------+------+--------------------+
3 rows in set (0.00 sec)
Code
package main
import (
"database/sql"
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"time"
)
type User struct {
ID int64
Age int64
Name string
Email string
}
type userModel struct {
ID int64
Name string
}
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
var UserModels []userModel
db.Model(User{
}).Find(&UserModels)
fmt.Println(UserModels)
}
func connect() (db *gorm.DB,sqlDB *sql.DB,err error) {
dsn := "root:[email protected](127.0.0.1:3306)/crow?charset=utf8&parseTime=True&loc=Local"
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
})
sqlDB,_ = db.DB()
if err != nil {
fmt.Printf(err.Error())
defer sqlDB.Close()
}else {
fmt.Printf("OK\n")
sqlDB.SetMaxIdleConns(10)
sqlDB.SetMaxOpenConns(100)
sqlDB.SetConnMaxLifetime(time.Hour)
}
return
}
Results output
OK
[{
1 LiuBei} {
2 GuanYu} {
3 ZhangFei}]
1.2 Find To Map
Define a Map To receive data
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
var users map[string]interface{
}
db.Table("users").Find(&users)
fmt.Println(users)
}
2. Subquery
db.Where("age > (?)", db.Table("users").Select("AVG(age)")).Find(&users)
// SELECT * FROM "users" WHERE age > (SELECT AVG(age) FROM "users");
- Example
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
var users []User
db.Where("age > (?)", db.Table("users").Select("AVG(age)")).Find(&users)
fmt.Println(users)
}
- Query results
OK
[{
1 28 LiuBei [email protected]}]
3. Group/Having
3.1 Group
Sum up 、 Grouping of average value, etc
db.Table("users").Select("AVG(age) as avg_age","company").Group("company").Find(&users)
Complete example
Find the average age of each company in the table below
- Data sheet
mysql> select * from users;
+----+----------+------+--------------------+---------+
| id | name | age | email | company |
+----+----------+------+--------------------+---------+
| 1 | LiuBei | 28 | liubei@xishu.com | shu |
| 2 | GuanYu | 22 | guanyu@xishu.com | shu |
| 3 | ZhangFei | 20 | zhangfei@xishu.com | shu |
| 4 | SunQuan | 22 | sunquan@dongwu.com | wu |
| 5 | ZhouYu | 15 | zhouyu@dongwu.com | wu |
+----+----------+------+--------------------+---------+
5 rows in set (0.00 sec)
- Code
package main
import (
"database/sql"
"fmt"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"time"
)
type User struct {
ID int64
Age int64
Name string
Email string
Company string
}
type groupBy struct {
AvgAge float64
Company string
}
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
var users []groupBy
db.Table("users").Select("AVG(age) as avg_age","company").Group("company").Find(&users)
fmt.Println(users)
}
func connect() (db *gorm.DB,sqlDB *sql.DB,err error) {
dsn := "root:[email protected](127.0.0.1:3306)/crow?charset=utf8&parseTime=True&loc=Local"
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
})
sqlDB,_ = db.DB()
if err != nil {
fmt.Printf(err.Error())
defer sqlDB.Close()
}else {
fmt.Printf("OK\n")
sqlDB.SetMaxIdleConns(10)
sqlDB.SetMaxOpenConns(100)
sqlDB.SetConnMaxLifetime(time.Hour)
}
return
}
- Output results
OK
[{
23.3333 shu} {
18.5 wu}]
3.2 Having
Yes Group Filter the results of . The result obtained in the above example , use Having The average value obtained is greater than 20 Result .
db.Table("users").Select("AVG(age) as avg_age","company").Group("company").Having("avg_age > ?",20).Find(&users)
4. Variable
4.1 Use sql.Named Definition
db.Where("age > @age AND company = @company", sql.Named("company", "shu"),sql.Named("age", 20)).Find(&users)
4.2 Use map Defining variables
db.Where("age > @age AND company = @company",map[string]interface{
}{
"company": "shu","age":20}).First(&users)
- Example
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
var users []User
checkUser := map[string]interface{
}{
"company":"shu",
"age":20,
}
db.Where("age > @age AND company = @company",checkUser).First(&users)
fmt.Println(users)
}
5. use Rows() iteration
Use
use Rows() Record data ----> rows.Next() Read line by line -----> use ScanRows Assign to structureExample
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
rows, _ := db.Model(&User{
}).Where("company = ?", "shu").Rows()
defer rows.Close()
for rows.Next() {
var user User
// ScanRows Method is used to scan a line of records to the structure
db.ScanRows(rows, &user)
fmt.Println(user)
}
}
6. Check hook
Write a query hook , When the query result field
Company
It's empty time , Replace with " Group "
func (u *User) AfterFind(tx *gorm.DB) (err error) {
if u.Company == "" {
u.Company = "qun"
}
return
}
7. Pluck( Single column query )
- effect
Query single column data , And receive with a slice - Examples
db.Model(&User{
}).Pluck("name", &names)
- Code
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
var names []string
db.Model(&User{
}).Pluck("name", &names)
fmt.Println(names)
}
- Output
[LiuBei GuanYu ZhangFei YuJi ZhaoYun]
8. Scopes( Call the query function )
8.1 Use
- effect
We can use Scopes Call the pre created function . - Examples
db.Scopes( function 1, function 2).Find(&users)
8.2 Example
- Create a function
Create a function to query the age of about 20 Year old user data
func ageGT20db (db *gorm.DB) *gorm.DB {
return db.Where("age > ?",20)
}
- Call function
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
var users []User
db.Scopes(ageGT20db).Find(&users)
fmt.Println(users)
}
9. Count
effect
Count the number of data foundCode
func main() {
db,sqlDB,_ := connect()
defer sqlDB.Close()
var count int64
var users []User
db.Find(&users).Count(&count)
fmt.Println(count)
}
边栏推荐
- 原生表格-滚动-合并功能
- CesiumJS 2022^ 源码解读[7] - 3DTiles 的请求、加载处理流程解析
- Detailed and not wordy. Share the win10 tutorial of computer reinstallation system
- 1.4 learn more about functions
- P5.js development - setting
- Chapter 1: find the factorial n of n!
- Microservice framework - frequently asked questions
- IPv6 experiment
- Make a simple text logo with DW
- Basic command of IP address configuration ---ip V4
猜你喜欢
2022 Xinjiang latest construction eight members (standard members) simulated examination questions and answers
[Yu Yue education] basic reference materials of manufacturing technology of Shanghai Jiaotong University
[effective Objective-C] - block and grand central distribution
Commands related to files and directories
Chapter 20: y= sin (x) /x, rambling coordinate system calculation, y= sin (x) /x with profile graphics, Olympic rings, ball rolling and bouncing, water display, rectangular optimization cutting, R que
2.2 integer
MPLS configuration
2022-07-02 网工进阶(十五)路由策略-Route-Policy特性、策略路由(Policy-Based Routing)、MQC(模块化QoS命令行)
The 29th day of force deduction (DP topic)
Point cloud data denoising
随机推荐
Microservice knowledge sorting - search technology and automatic deployment technology
Micro service knowledge sorting - three pieces of micro Service Technology
2.4 conversion of different data types
2.5 conversion of different data types (2)
2022-06-27 网工进阶(十二)IS-IS-开销类型、开销计算、LSP的处理机制、路由撤销、路由渗透
Win10 share you don't have permission
1.5 learn to find mistakes first
2022-06-25 网工进阶(十一)IS-IS-三大表(邻居表、路由表、链路状态数据库表)、LSP、CSNP、PSNP、LSP的同步过程
JMeter connection database
2.1 use of variables
Leetcode daily question solution: 540 A single element in an ordered array
4. Data splitting of Flink real-time project
Global and Chinese market of two in one notebook computers 2022-2028: Research Report on technology, participants, trends, market size and share
Global and Chinese markets of active matrix LCD 2022-2028: Research Report on technology, participants, trends, market size and share
Realize user registration and login
Machine learning support vector machine SVM
Print linked list from end to end
3. Data binding
Global and Chinese market of high temperature Silver sintering paste 2022-2028: Research Report on technology, participants, trends, market size and share
Ruby replaces gem Alibaba image