1

I have the following list of parameters:

params := [(p_1, m_1), ..., (p_n, m_n)]  // p_i, m_i : int

Now I want to build a query which go trough the list and match parmeters: (the part after for is a pseudocode which I want to write in PostgreSQL 9.4)

SELECT * FROM X WHERE p = p_i AND m = m_i  for (p_i, m_i) in params

How to write this query in Go (using jmoiron.github.io/sqlx or standard database/sql)?

type Param struct {
    P, M int
}
params := []Param{{1,2}, {3,4}}
// ???
4

1 回答 1

1

As noted in comments, IN check should satisfy your needs:

Go over params to generate IN part of query:

paramStr := make([]string, len(params), len(params))
for i, p := range params {
    paramStr[i] = fmt.Sprintf("(%d, %d)", p.P, p.M)
}

Then, join params and execute it:

err := dbm.Select(&rows, "SELECT * FROM X WHERE (p, m) IN (%s)",
        strings.Join(paramStr, ","))

Here, for select, I used modl which is a utility on top of sqlx.

于 2015-07-09T12:44:56.907 回答