Home >Backend Development >Golang >How to sort database records in Golang?

How to sort database records in Golang?

WBOY
WBOYOriginal
2024-06-03 13:30:57589browse

In Golang, query results can be sorted by using the ORDER BY clause in the database/sql package. Syntax: func (db *DB) Query(query string, args ...interface{}) (*Rows, error) Sorting example: SELECT * FROM users ORDER BY name ASC Other sorting options: DESC (descending), multiple columns (Comma separated), NULL value sort order (NULLS FIRST or NULLS LAST) Practical case: Sort orders in descending order by "order_date": SELECT * FROM orders ORDER BY order_date DESC.

如何对 Golang 中的数据库记录进行排序?

How to sort database records in Golang?

When using the database/sql package to operate the database in Golang, you can use the ORDER BY clause to sort the query results.

Syntax:

func (db *DB) Query(query string, args ...interface{}) (*Rows, error)

Sort example:

The following example shows how to sort the Records sorted by "name" column in ascending order:

package main

import (
    "database/sql"
    "fmt"

    _ "github.com/go-sql-driver/mysql"
)

func main() {
    // 连接到数据库
    db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/database")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    // 构建查询
    query := `SELECT * FROM users ORDER BY name ASC`

    // 执行查询
    rows, err := db.Query(query)
    if err != nil {
        panic(err)
    }
    defer rows.Close()

    // 遍历结果
    for rows.Next() {
        var id int
        var name, email string
        if err := rows.Scan(&id, &name, &email); err != nil {
            panic(err)
        }
        fmt.Printf("%d %s %s\n", id, name, email)
    }
}

Other sorting options:

  • DESC: Sort in descending order
  • Multiple columns: Use commas to separate multiple columns, for example: ORDER BY name DESC, age ASC
  • NULL value: Use NULLS FIRST or NULLS LAST Specifies whether to place NULL values ​​at the beginning or end of the result set

Practical case:

Suppose we have an "orders" table with columns "order_id", "customer_id" and "order_date". We can write a Golang program to sort orders by "order_date" in descending order:

package main

import (
    "database/sql"
    "fmt"

    _ "github.com/go-sql-driver/mysql"
)

func main() {
    // 连接到数据库
    db, err := sql.Open("mysql", "user:password@tcp(127.0.0.1:3306)/database")
    if err != nil {
        panic(err)
    }
    defer db.Close()

    // 构建查询
    query := `SELECT * FROM orders ORDER BY order_date DESC`

    // 执行查询
    rows, err := db.Query(query)
    if err != nil {
        panic(err)
    }
    defer rows.Close()

    // 遍历结果
    for rows.Next() {
        var orderID, customerID int
        var orderDate string
        if err := rows.Scan(&orderID, &customerID, &orderDate); err != nil {
            panic(err)
        }
        fmt.Printf("%d %d %s\n", orderID, customerID, orderDate)
    }
}

The above is the detailed content of How to sort database records in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn