当前位置:网站首页>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)
}
边栏推荐
- 1.4 learn more about functions
- Use unique_ PTR forward declaration? [repetition] - forward declaration with unique_ ptr? [duplicate]
- Chapter 2: find the number of daffodils based on decomposition, find the number of daffodils based on combination, find the conformal number in [x, y], explore the n-bit conformal number, recursively
- Chapter 1: find all factorial sums, Grand Prix site unified programming, three factorial sums, graphic point scanning, recursive factorial n of n!, Find the factorial n of n!, King Shehan miscalculate
- JMeter connection database
- AI enhanced safety monitoring project [with detailed code]
- 2022-07-02 advanced network engineering (XV) routing policy - route policy feature, policy based routing, MQC (modular QoS command line)
- Nacos usage of micro services
- IP address is such an important knowledge that it's useless to listen to a younger student?
- 4. Data splitting of Flink real-time project
猜你喜欢

PR FAQ: how to set PR vertical screen sequence?

BOC protected amino acid porphyrins TAPP ala BOC, TAPP Phe BOC, TAPP Trp BOC, Zn · TAPP ala BOC, Zn · TAPP Phe BOC, Zn · TAPP Trp BOC Qiyue

Phpstudy set LAN access

2022 Xinjiang latest road transportation safety officer simulation examination questions and answers
![Cesiumjs 2022 ^ source code interpretation [7] - Analysis of the request and loading process of 3dfiles](/img/70/6fd00146418e5d481e951d51428990.png)
Cesiumjs 2022 ^ source code interpretation [7] - Analysis of the request and loading process of 3dfiles

Don't be afraid of no foundation. Zero foundation doesn't need any technology to reinstall the computer system

Exercises of function recursion

Promethus

Vscode reports an error according to the go plug-in go get connectex: a connection attempt failed because the connected party did not pro

Chapter 1: find the algebraic sum of odd factors, find the same decimal sum s (D, n), simplify the same code decimal sum s (D, n), expand the same code decimal sum s (D, n)
随机推荐
unittest框架基本使用
Global and Chinese market of rubidium standard 2022-2028: Research Report on technology, participants, trends, market size and share
4. Data splitting of Flink real-time project
P5.js development - setting
44. Concurrent programming theory
【leetcode】1027. Longest arithmetic sequence (dynamic programming)
PR notes:
MPLS configuration
Sparse matrix (triple) creation, transpose, traversal, addition, subtraction, multiplication. C implementation
[raid] [simple DP] mine excavation
Wechat applet quick start (including NPM package use and mobx status management)
Titles can only be retrieved in PHP via curl - header only retrieval in PHP via curl
Micro service knowledge sorting - asynchronous communication technology
Realize user registration and login
Assign the CMD command execution result to a variable
Bool blind note - score query
JMeter plug-in installation
Utilisation de base du cadre unitest
Explore the internal mechanism of modern browsers (I) (original translation)
Global and Chinese market of electrolyte analyzers 2022-2028: Research Report on technology, participants, trends, market size and share