当前位置:网站首页>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
CompanyIt'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)
}
边栏推荐
- 5. MVVM model
- Blue Bridge Cup: the fourth preliminary - "simulated intelligent irrigation system"
- Microsoft: the 12th generation core processor needs to be upgraded to win11 to give full play to its maximum performance
- BOC protected phenylalanine zinc porphyrin (Zn · TAPP Phe BOC) / iron porphyrin (Fe · TAPP Phe BOC) / nickel porphyrin (Ni · TAPP Phe BOC) / manganese porphyrin (Mn · TAPP Phe BOC) Qiyue Keke
- Xctf attack and defense world crypto advanced area best_ rsa
- Don't be afraid of no foundation. Zero foundation doesn't need any technology to reinstall the computer system
- Class loading process
- 2022-06-25 网工进阶(十一)IS-IS-三大表(邻居表、路由表、链路状态数据库表)、LSP、CSNP、PSNP、LSP的同步过程
- How can the outside world get values when using nodejs to link MySQL
- Teach you how to quickly recover data by deleting recycle bin files by mistake
猜你喜欢

JMeter plug-in installation

CMD implements the language conversion of locale non Unicode programs

Detailed and not wordy. Share the win10 tutorial of computer reinstallation system

PR FAQ: how to set PR vertical screen sequence?

The 29th day of force deduction (DP topic)

Kubernetes cluster builds efk log collection platform

Camera calibration (I): robot hand eye calibration

FPGA learning notes: vivado 2019.1 project creation

2.4 conversion of different data types

5- (4-nitrophenyl) - 10,15,20-triphenylporphyrin ntpph2/ntppzn/ntppmn/ntppfe/ntppni/ntppcu/ntppcd/ntppco and other metal complexes
随机推荐
What is the difference between a kill process and a close process- What are the differences between kill process and close process?
Class loading process
PR 2021 quick start tutorial, how to create new projects and basic settings of preferences?
How to improve data security by renting servers in Hong Kong
Realize user registration and login
Implementation of stack
5. MVVM model
44. Concurrent programming theory
Micro service knowledge sorting - asynchronous communication technology
2022-06-30 网工进阶(十四)路由策略-匹配工具【ACL、IP-Prefix List】、策略工具【Filter-Policy】
Native table - scroll - merge function
How can the outside world get values when using nodejs to link MySQL
4. Data splitting of Flink real-time project
2022-06-30 網工進階(十四)路由策略-匹配工具【ACL、IP-Prefix List】、策略工具【Filter-Policy】
2.3 other data types
6006. Take out the minimum number of magic beans
Leetcode daily question solution: 540 A single element in an ordered array
Virtual machine installation deepin system
Promethus
原生表格-滚动-合并功能