我有一个SQL查询来获取列的所有不同值
SELECT DISTINCT ON (column1) column1, column2, column3, column4 FROM table1 WHERE column1=$1
现在我要做的是生成这样的响应:
{
"column1" : ["value1", "value2", "value3", "value4"],
"column2" : ["value1", "value2", "value3", "value4"],
...
}
我遇到的问题是如何将查询结果扫描到结果图中:
rows, err = sql.DB.Query("SELECT DISTINCT ON (column1) column1, column2, column3, column4 FROM table1 WHERE column1=$1", id)
if err != nil {
return err
}
defer rows.Close()
result := make(map[string][]string)
cols,_ := rows.Columns()
for _, colName := range cols {
result[colName] = []string{}
}
for rows.Next() {
columns := make([]interface{}, len(cols))
columnPointers := make([]interface{}, len(cols))
for i := range columns {
columnPointers[i] = &columns[i]
}
if err := rows.Scan(columnPointers...); err != nil {
return result, err
}
for i, colName := range cols {
val := columns[i]
if val != nil {
if val.(string) != "" {
result[colName] = append(params[colName], val.(string))
}
}
}
}
return result, nil
编辑:感谢question from @Arne,我得以弄清楚。使用完整的工作版本更新了我的问题。