Go and IN clause in Postgres

前端 未结 2 1837
傲寒
傲寒 2020-11-27 07:32

I am trying to execute the following query against the PostgreSQL database in Go using pq driver:

SELECT COUNT(id)
FROM tags
WHERE id IN (1, 2, 3)

2条回答
  •  一生所求
    2020-11-27 08:09

    This is not really a Golang issue, you are using a string to compare to integer (id) in your SQL request. That means, SQL receive:

    SELECT COUNT(id)
    FROM tags
    WHERE id IN ("1, 2, 3")
    

    instead of what you want to give it. You just need to convert your tags into integer and passe it to the query.

    EDIT: Since you are trying to pass multiple value to the query, then you should tell it:

    params := make([]string, 0, len(tags))
    for i := range tags {
        params = append(params, fmt.Sprintf("$%d", i+1))
    }
    query := fmt.Sprintf("SELECT COUNT(id) FROM tags WHERE id IN (%s)", strings.Join(params, ", "))
    

    This will end the query with a "($1, $2, $3...", then convert your tags as int:

    values := make([]int, 0, len(tags))
    for _, s := range tags {
        val, err := strconv.Atoi(s)
        if err != nil {
            // Do whatever is required with the error
            fmt.Println("Err : ", err)
        } else {
            values = append(values, val)
        }
    }
    

    And finally, you can use it in the query:

    Db.QueryRow(query, values...)
    

    This should do it.

提交回复
热议问题