Select [PostgreSQL MySQL]

    Example

    To select into a struct, define a and use SelectQueryopen in new window:

    1. err := db.NewSelect().Model(book).Where("id = ?", 123).Scan(ctx)
    1. count, err := db.NewSelect().Model((*User)(nil)).Count(ctx)

    Because selecting and counting rows is a common operation, Bun also provides :

    1. var users []User
    2. count, err := db.NewSelect().Model(&users).Limit(20).ScanAndCount(ctx)
    3. if err != nil {
    4. }
    5. fmt.Println(users, count)

    EXISTS

    1. SELECT EXISTS (SELECT * FROM users WHERE name LIKE '%foo%')

    To select a book and manually join the book author:

    1. err := db.NewSelect().
    2. Model(book).
    3. ColumnExpr("book.*").
    4. ColumnExpr("a.id AS author__id, a.name AS author__name").
    5. Join("JOIN authors AS a ON a.id = book.author_id").
    6. OrderExpr("book.id ASC").
    7. Limit(1).
    8. Scan(ctx)
    1. FROM books
    2. JOIN authors AS a ON a.id = book.author_id
    3. LIMIT 1
    1. JOIN authors AS a ON a.id = book.author_id AND a.deleted_at IS NULL

    Subqueries

    You can use Bun queries (including INSERT, UPDATE, and DELETE queries) as a subquery:

    1. subq := db.NewSelect().Model((*Book)(nil)).Where("author_id = ?", 1)
    2. err := db.NewSelect().Model().TableExpr("(?) AS book", subq).Scan(ctx, &books)
    1. SELECT * FROM (
    2. SELECT "book"."id", "book"."title", "book"."text"
    3. ) AS book