I have a table that contains 3 fields:
user_id
, name
, value
There is no primary key in the table, the user_id
can have duplicate values, For the name
there are enumerated fields age, job and salary.
user_id | name | value
------------------------
1 | age | 20
------------------------
1 | job | IT
------------------------
2 | salary | 20000
------------------------
2 | job | Dev
------------------------
2 | age | 30
------------------------
I want to create a structure like below
user_id | age | job | salary
----------------------------
1 | 20 | IT | NULL
----------------------------
2 | 30 | Dev | 20000
----------------------------
Main query :
rows, err := db1.Query("select user_id from main_users");
for rows.Next() {
rows.scan(&user_id)
id := reflect.ValueOf(user_id)
user_idvalue := id.Interface().(int)
rows1, err1 := db1.Query("select age from users where user_id=$1", user_idvalue)
rows2, err2 := db1.Query("select job from users where user_id=$1", user_idvalue)
rows3, err3 := db1.Query("select salary from users where user_id=$1", user_idvalue)
}
I am stuck at the part of with each result line the id compared for the 3 others queries and to be shown as one table.
First, the queries should look like this.
userAgeValues, err1 := db1.Query("select value from users where user_id=$1 and name=\"age\";", user_idvalue)
userJobValues, err2 := db1.Query("select value from users where user_id=$1 and name=\"job\"", user_idvalue)
userSalaryValues, err3 := db1.Query("select value from users where user_id=$1 and name=\"salary\"", user_idvalue)
Then you have these values to do with what you want. Based on your description there should only be 1 row in each of these results.
you can create a map with key= user_id and value = user struct
define a user struct and map :
type user struct{
age string
salary string
job string
}
user := make(map[int]user)
get the whole data from the table and start loading it into your map