0

我尝试查询用户 ID 列表。我正在使用 Go Pq库。

func ListUsers(userIDs []interface{}) (users []User, err error) {
    stm := `SELECT
    U.id,
    (
        CASE WHEN TRIM(UP.first_name || ' ' || UP.last_name) = '' THEN U.id :: TEXT ELSE UP.first_name || ' ' || UP.last_name END
        ) as avatar_name,
FROM
    users AS U
        JOIN user_profiles UP ON UP.user_id = U.id
WHERE
        U.id IN ($1);`

    rows, err := postgresql.Instance.Query(stm, userIDs)
    defer rows.Close()
    if err != nil && err != sql.ErrNoRows {
        return
    }

    if err == sql.ErrNoRows {
        return users, nil
    }

    for rows.Next() {
        var (
            id         int
            AvatarName string
        )
        err = rows.Scan(&id, &AvatarName)
        if err != nil {
            return nil, err
        }

        users = append(users, User{ID: id, AvatarName: AvatarName})
    }

    return users, nil
}

当我运行它时,它给出了错误转换参数 $1 type: unsupported type []interface {}, a slice of interface

4

1 回答 1

2
  • pq.Array包裹切片。
  • 更改IN ($1)= any($1)可以使用数组值。

这是代码:

    stm := `SELECT
    U.id,
    (
        CASE WHEN TRIM(UP.first_name || ' ' || UP.last_name) = '' THEN U.id :: TEXT ELSE UP.first_name || ' ' || UP.last_name END
        ) as avatar_name,
FROM
    users AS U
        JOIN user_profiles UP ON UP.user_id = U.id
WHERE
        U.id = any($1);`
    rows, err := postgresql.Instance.Query(stm, pq.Array(userIDs))
于 2019-10-31T01:36:52.407 回答