在SQL Server中使用内连接(inner join)。

huangapple go评论85阅读模式
英文:

Use an inner join in SQL Server

问题

我正在使用SQL Server和Go进行练习,现在我正在对一个表进行查询,该表与两个表进行内连接,主表是用户表,内连接的表是用户状态表和用户角色表,但是在显示所有用户的列表时,它显示了我正在进行内连接的另外两个表的对象。

这是我的结构:

type User struct {
    Id_User       int64     `json:"id_user,omitempty"`
    Name          string    `json:"name,omitempty"`
    NameSecond    string    `json:"name_second,omitempty"`
    Surname       string    `json:"surname,omitempty"`
    SurnameSecond string    `json:"surname_second,omitempty"`
    Email         string    `json:"email,omitempty"`
    Password      string    `json:"password,omitempty"`
    Id_RoleUser   UserRole  `json:"id_roleUser,omitempty"`
    Id_UserState  UserState `json:"id_userState,omitempty"`
    CreatedAt     time.Time `json:"created_at,omitempty"`
    UpdatedAt     time.Time `json:"crated_at,omitempty"`
}

我知道它将UserRole和UserState结构显示为对象,因为我在指定它们,但是有没有办法只显示名称,就像结构的另一个字段一样?

这是我的代码:

func ListUser(w http.ResponseWriter, r *http.Request) {
    w.Header().Add("Content-Type", "application/json")

    var user model.User

    db := storage.Connection()
    tsql := `
    SELECT
        Id_User,
        U.Name + ' ' + NameSecond,
        Surname + ' ' + SurnameSecond,
        Email,
        UR.Name,
        US.Name
    FROM
        Users U
            INNER JOIN UserRoles UR ON UR.Id_RoleUser = U.Id_RoleUser
            INNER JOIN UserStates US ON US.Id_UserState = U.Id_UserState
    `

    rows, err := db.QueryContext(context.Background(), tsql)
    if err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    defer rows.Close()
    users := []model.User{}

    for rows.Next() {
        if err := rows.Scan(&user.Id_User, &user.Name, &user.Surname, &user.Email, &user.Id_RoleUser.Name, &user.Id_UserState.Name); err != nil {
            http.Error(w, err.Error(), http.StatusBadRequest)
            return
        }
        users = append(users, user)
    }

    if err := rows.Err(); err != nil {
        http.Error(w, err.Error(), http.StatusBadRequest)
        return
    }

    json.NewEncoder(w).Encode(users)
}

这是生成的JSON:

{
  "id_user": 5,
  "name": "Joan Sebastian",
  "surname": "Tovar Osorio",
  "email": "jsto@hotmail.com",
  "id_roleUser": {
    "name": "Desarrollador",
    "created_at": "0001-01-01T00:00:00Z"
  },
  "id_userState": {
    "name": "Inactivo",
    "created_at": "0001-01-01T00:00:00Z"
  },
  "created_at": "0001-01-01T00:00:00Z",
  "crated_at": "0001-01-01T00:00:00Z"
}
英文:

I am doing a practice with SQL Server and Go, and now I am making a query on a table which has an inner join against two tables, the main table is user and the tables to which it is performing the inner join are user state and user roles, but at the moment of being able to show a list of all the users, it shows me an object from the other two tables which I am doing the inner join.

This is my structure:

type User struct {
	Id_User       int64     `json:"id_user,omitempty"`
	Name          string    `json:"name,omitempty"`
	NameSecond    string    `json:"name_second,omitempty"`
	Surname       string    `json:"surname,omitempty"`
	SurnameSecond string    `json:"surname_second,omitempty"`
	Email         string    `json:"email,omitempty"`
	Password      string    `json:"password,omitempty"`
	Id_RoleUser   UserRole  `json:"id_roleUser,omitempty"`
	Id_UserState  UserState `json:"id_userState,omitempty"`
	CreatedAt     time.Time `json:"created_at,omitempty"`
	UpdatedAt     time.Time `json:"crated_at,omitempty"`
}

I know that it is showing me the UserRole and UserState structures as an object, because then I specify them but there is no way to be able to show only the name as if it were another field of the structure?

This my code:

func ListUser(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("Content-Type", "application/json")

	var user model.User

	db := storage.Connection()
	tsql := `
	SELECT
		Id_User,
		U.Name + ' ' + NameSecond,
		Surname + ' ' + SurnameSecond,
		Email,
		UR.Name,
		US.Name
	FROM
		Users U
			INNER JOIN UserRoles UR ON UR.Id_RoleUser = U.Id_RoleUser
			INNER JOIN UserStates US ON US.Id_UserState = U.Id_UserState
	`

	rows, err := db.QueryContext(context.Background(), tsql)
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	defer rows.Close()
	users := []model.User{}

	for rows.Next() {
		if err := rows.Scan(&user.Id_User, &user.Name, &user.Surname, &user.Email, &user.Id_RoleUser.Name, &user.Id_UserState.Name); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}
		users = append(users, user)
	}

	if err := rows.Err(); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}

	json.NewEncoder(w).Encode(users)
}

This my JSON generated:

{
  "id_user": 5,
  "name": "Joan Sebastian",
  "surname": "Tovar Osorio",
  "email": "jsto@hotmail.com",
  "id_roleUser": {
    "name": "Desarrollador",
    "created_at": "0001-01-01T00:00:00Z"
  },
  "id_userState": {
    "name": "Inactivo",
    "created_at": "0001-01-01T00:00:00Z"
  },
  "created_at": "0001-01-01T00:00:00Z",
  "crated_at": "0001-01-01T00:00:00Z"
}

答案1

得分: 2

你可以实现json.Marshaler接口,并为另一个具有所需字段的结构定义MarshalJson函数。

type MyUser struct {
    Id_User       int64     `json:"id_user,omitempty"`
    Name          string    `json:"name,omitempty"`
    NameSecond    string    `json:"name_second,omitempty"`
    Surname       string    `json:"surname,omitempty"`
    SurnameSecond string    `json:"surname_second,omitempty"`
    Email         string    `json:"email,omitempty"`
    Password      string    `json:"password,omitempty"`
    RoleUserName  string    `json:"roleUser_name,omitempty"`
    UserStateName string    `json:"userState_name,omitempty"`
    CreatedAt     time.Time `json:"created_at,omitempty"`
    UpdatedAt     time.Time `json:"crated_at,omitempty"`
}

func (u *User) MarshalJSON() ([]byte, error) {
    mu := MyUser{
        Id_User:       u.Id_User,
        Name:          u.Name,
        NameSecond:    u.NameSecond,
        Surname:       u.Surname,
        SurnameSecond: u.SurnameSecond,
        Email:         u.Email,
        Password:      u.Password,
        RoleUserName:  u.Id_RoleUser.Name,
        UserStateName: u.Id_UserState.Name,
        CreatedAt:     u.CreatedAt,
        UpdatedAt:     u.UpdatedAt,
    }
    return json.Marshal(mu)
}
英文:

EDIT: You can implement the json.Marshaler interface and define the MarshalJson function for another struct which has your required fields.

type MyUser struct {
    Id_User       int64     `json:"id_user,omitempty"`
    Name          string    `json:"name,omitempty"`
    NameSecond    string    `json:"name_second,omitempty"`
    Surname       string    `json:"surname,omitempty"`
    SurnameSecond string    `json:"surname_second,omitempty"`
    Email         string    `json:"email,omitempty"`
    Password      string    `json:"password,omitempty"`
    RoleUserName  string  `json:"roleUser_name,omitempty"`
    UserStateName  string `json:"userState_name,omitempty"`
    CreatedAt     time.Time `json:"created_at,omitempty"`
    UpdatedAt     time.Time `json:"crated_at,omitempty"`
}

func (u *User) MarshalJSON() ([]byte, error) {
	mu := MyUser{
		Id_User:       u.Id_User,
		Name:          u.Name,
		NameSecond:    u.NameSecond,
		Surname:       u.Surname,
		SurnameSecond: u.SurnameSecond,
		Email:         u.Email,
		Password:      u.Password,
		RoleUserName:  u.Id_RoleUser.Name,
		UserStateName: u.Id_UserState.Name,
		CreatedAt:     u.CreatedAt,
		UpdatedAt:     u.UpdatedAt,
	}
	return json.Marshal(mu)
}

huangapple
  • 本文由 发表于 2021年7月29日 04:43:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/68567124.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定