LoginSignup
1
1

More than 1 year has passed since last update.

[golang] GormでDISTINCTを使う

Last updated at Posted at 2022-11-26

はじめに

GormでMySQLを操作していたところ、DISTINCTを使いたくなった。
GORMのサイトをみてやってみたけど上手くいかなかったので、
色々自分で試す。上手くいく方法が見つかったので、そのメモ。

結論

Select()の取得対象指定の際に、頭に"DISTINCT "を付与する

ソースコード

確認時のソースコード

package main

import (
    "fmt"
    "github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

const (
    TBL_TEST string = "Test"
)

// 元のテーブル
type Test struct {
    Id		uint32  `gorm:"column:ID" json:ID`
    Name	string	`gorm:"column:name" json:name`
    Age	    uint32	`gorm:"column:age" json:age`
}

// 取り出したい対象
type result struct {
    Age	    uint32	`gorm:"column:age" json:age`
}

func main() {
	var rslt []result = []result{}
    var dbCnct *gorm.DB

    // DBへの接続処理(省略)
  
    err := dbCnct.Debug().Table(TBL_TEST).Select("DISTINCT " + TBL_TEST + ".age").Scan(&rslt).Error
    fmt.Println(rslt)
}
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1