转换参数 $1 类型:不支持的类型 []interface {},接口的一部分
Converting argument $1 type: unsupported type []interface {}, a slice of interface
我尝试查询用户 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 ();`
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
}
当我运行这个它给出错误converting argument $1 type: unsupported type []interface {}, a slice of interface
- 用pq.Array包裹切片。
- 将
IN ()
更改为= any()
以便可以使用数组值。
代码如下:
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();`
rows, err := postgresql.Instance.Query(stm, pq.Array(userIDs))
我尝试查询用户 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 ();`
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
}
当我运行这个它给出错误converting argument $1 type: unsupported type []interface {}, a slice of interface
- 用pq.Array包裹切片。
- 将
IN ()
更改为= any()
以便可以使用数组值。
代码如下:
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();`
rows, err := postgresql.Instance.Query(stm, pq.Array(userIDs))