当前位置:网站首页>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)
}
边栏推荐
- Micro service knowledge sorting - cache technology
- Blue Bridge Cup: the fourth preliminary - "simulated intelligent irrigation system"
- Oak-d raspberry pie cloud project [with detailed code]
- BOC protected alanine porphyrin compound TAPP ala BOC BOC BOC protected phenylalanine porphyrin compound TAPP Phe BOC Qi Yue supply
- Global and Chinese market of micro positioning technology 2022-2028: Research Report on technology, participants, trends, market size and share
- BOC protected tryptophan zinc porphyrin (Zn · TAPP Trp BOC) / copper porphyrin (Cu · TAPP Trp BOC) / cobalt porphyrin (cobalt · TAPP Trp BOC) / iron porphyrin (Fe · TAPP Trp BOC) / Qiyue supply
- NFT without IPFs and completely on the chain?
- Global and Chinese markets of polyimide tubes for electronics 2022-2028: Research Report on technology, participants, trends, market size and share
- Exercises of function recursion
- About unregistered transfer login page
猜你喜欢
Professional interpretation | how to become an SQL developer
2022 Xinjiang latest construction eight members (standard members) simulated examination questions and answers
2022 - 06 - 30 networker Advanced (XIV) Routing Policy Matching Tool [ACL, IP prefix list] and policy tool [Filter Policy]
Typora charges, WTF? Still need support
Chapter 1: find the factorial n of n!
Oak-d raspberry pie cloud project [with detailed code]
Commands related to files and directories
Change deepin to Alibaba image source
2.1 use of variables
2022 Xinjiang latest road transportation safety officer simulation examination questions and answers
随机推荐
Micro service knowledge sorting - asynchronous communication technology
Global and Chinese market of electrolyte analyzers 2022-2028: Research Report on technology, participants, trends, market size and share
BOC protected alanine zinc porphyrin Zn · TAPP ala BOC / alanine zinc porphyrin Zn · TAPP ala BOC / alanine zinc porphyrin Zn · TAPP ala BOC / alanine zinc porphyrin Zn · TAPP ala BOC supplied by Qiyu
Derivation of decision tree theory
Titles can only be retrieved in PHP via curl - header only retrieval in PHP via curl
IPv6 experiment
PR notes:
PR 2021 quick start tutorial, how to create a new sequence and set parameters?
Initialization and instantiation
App compliance
【leetcode】1027. Longest arithmetic sequence (dynamic programming)
How can the outside world get values when using nodejs to link MySQL
2166. Design bit set
4. Data splitting of Flink real-time project
PR 2021 quick start tutorial, material import and management
Xctf attack and defense world crypto advanced area best_ rsa
Today's work summary and plan: February 14, 2022
Part 27 supplement (27) buttons of QML basic elements
Basic command of IP address configuration ---ip V4
2022-06-25 advanced network engineering (XI) IS-IS synchronization process of three tables (neighbor table, routing table, link state database table), LSP, cSNP, psnp, LSP