How to join tables using join query in Golang?

WBOY
Release: 2024-06-05 11:10:25
Original
336 people have browsed it

Associative queries join tables to combine data from multiple tables through SQL queries. In Golang, use the sql.DB.Query() function to specify the query string and parameters. Different join types can be used, such as INNER JOIN, LEFT JOIN, RIGHT JOIN, and FULL OUTER JOIN, depending on the desired result set.

如何在 Golang 中使用关联查询连接表?

#How to use association query to join tables in Golang?

Joined queries are a method of combining rows from multiple tables to form a single result set. In Golang, you can use the sql.DB.Query() function to perform related queries.

Syntax:

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

Query parameters:

  • query: To be executed SQL query string.
  • args: List of arguments to replace placeholders in the query string.

Example:

Suppose we have two tables: users and orders, which pass user_id Column association. Let’s write a query to get the names of all users and the order numbers of their most recent orders:

package main

import (
    "database/sql"
    "fmt"

    _ "github.com/go-sql-driver/mysql" // 加载 MySQL 驱动程序
)

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

    // 准备查询语句
    query := `SELECT users.name, orders.order_number
                FROM users
                INNER JOIN orders ON users.user_id = orders.user_id
                ORDER BY orders.order_date DESC
                LIMIT 1`

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

    // 遍历结果行
    for rows.Next() {
        var name string
        var orderNumber string
        if err := rows.Scan(&name, &orderNumber); err != nil {
            panic(err)
        }
        fmt.Printf("%s's latest order: %s\n", name, orderNumber)
    }
}
Copy after login

Before executing the query, we need to prepare the query statement using the db.Query() function . We can then iterate through the result set row by row using the rows.Next() method and extract the column values ​​using the rows.Scan() method.

The query in this example uses the INNER JOIN keyword, which will only return rows that have matching rows in both tables. Other types of join queries include:

  • LEFT JOIN: Returns all rows from the left table, even if there are no matches in the right table.
  • RIGHT JOIN: Returns all rows from the right table, even if there are no matches in the left table.
  • FULL OUTER JOIN: Returns all rows from both tables.

The above is the detailed content of How to join tables using join query in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template