douwei9973
2015-07-09 09:04
浏览 55

如何在SQL选择查询中展开整数对列表

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}}
// ???

图片转代码服务由CSDN问答提供 功能建议

我有以下参数列表:

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

现在我想建立一个查询 遍历列表并匹配参数: ( for 之后的部分是我要在 PostgreSQL 9.4中编写的伪代码) < pre> SELECT * FROM X WHERE p = p_i AND m = m_i for params中的(p_i,m_i)

如何在Go中编写此查询( 使用 jmoiron.github.io/sqlx 或标准 database / sql )?

  type参数结构{
 P,M int 
} 
params:= [] Param {{1,2},{3,4}} 
 /  / ??? 
   
 
  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • doushi1960 2015-07-09 12:44
    已采纳

    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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题