0

我有一个项目类型和项目编号列表,如下所示:

items := models.ItemKeys{
        ItemKeys: []models.ItemKey{
            {
                ItemType:   "type1",
                ItemNumber: "10347114",
            },
            {
                ItemType:   "type2",
                ItemNumber: "40428383",
            },
            {
                ItemType:   "type3",
                ItemNumber: "90351753",
            },
        },
    }

我想产生这种查询:

SELECT * FROM item
WHERE (item_type, item_number) IN (('type1','10347114'), ('type2','40428383'), ('type3','90351753'))

值得一提的是,我正在使用 pq 包(https://github.com/lib/pq)。我碰巧发现有一种方法可以ANY代替。但是,当我尝试时,它说sql: converting argument $1 type: pq: Unable to convert models.ItemKeys to array

这是我当前的代码:

rows, err := r.Db.QueryContext(ctx, "SELECT * "+
        "FROM item "+
        "WHERE (item_type, item_number) = ANY($1) "+
        "AND deleted_dtime IS NULL", pq.Array(items))

有谁知道如何正确地做到这一点?

4

1 回答 1

0

您可以执行以下操作:

inSQL, args := "", []interface{}{}
for i, itemKey := range items.ItemKeys {
    n := i * 2
    inSQL += fmt.Sprintf("($%d,$%d),", n+1, n+2)
    args = append(args, itemKey.ItemType, itemKey.ItemNumber)
}
inSQL = inSQL[:len(inSQL)-1] // drop last ","

query := `SELECT * FROM item WHERE (item_type, item_number) IN (` + inSQL + `) AND deleted_dtime IS NULL`

// query: SELECT * FROM item WHERE (item_type, item_number) IN (($1,$2),($3,$4),($5,$6)) AND deleted_dtime IS NULL
// args: ["type1" "10347114" "type2" "40428383" "type3" "90351753"]

rows, err := r.Db.QueryContext(ctx, query, args...)
// ...
于 2022-02-23T14:58:22.507 回答