首页 > 解决方案 > mysql的语法数组

问题描述

将数据数组添加到数据库中的语法是什么,我为 postgresql 找到的是:pg.Array

 // "ins" is the SQL insert statement
ins := "INSERT INTO posts (title, tags) VALUES ($1, $2)"

// "tags" is the list of tags, as a string slice
tags := []string{"go", "goroutines", "queues"}

// the pq.Array function is the secret sauce
_, err = db.Exec(ins, "Job Queues in Go", pq.Array(tags))

标签: mysqlarrayspostgresqlgo

解决方案


我将在这里分解几点,这主要是由于您的问题不明确:

第一的

pq.ArrayPostgreSQL 中用于将数组值转换为安全列表,如以下语句:

db.Query(`SELECT * FROM t WHERE id = ANY($1)`, pq.Array([]int{235, 401}))

结果查询在哪里:

SELECT * FROM t WHERE id = ANY(235, 401)

这旨在帮助您从列表中安全地制作与类型无关的查询值,这不是您在问题中使用它的方式。

第二

如果您只是想将值编组到数据库列中的逗号分隔列表中,即:

| title   | tags                 |
|---------|----------------------|
| my post | go,goroutines,queues |

您不需要 SQL 驱动程序中的特殊函数。您只需要创建值,然后让准备好的语句做它的事情:

tags := []string{"go, goroutines, queues"}
q := "INSERT INTO posts (title, tags) VALUES ($1, $2)"
_, _ = db.Exec(q, "mypost", strings.Join(tags, ","))

第三

你可能会得到更好的服务,使用 MySQL 中的关系来完成你正在做的事情:

帖子
| id | title   |
|----|---------|
| 1  | my post |
标签
| id | tag        |
|----|------------|
| 1  | go         |
| 2  | goroutines |
| 3  | queues     |
帖子标签
| posts_id | tags_id |
|----------|---------|
| 1        | 1       |
| 1        | 2       |
| 1        | 3       |

这将通过不保存重复数据来帮助您节省空间,并且无需了解数据库中的序列化方法(另外,这就是关系数据库所做的)。然后,当您选择表时,您可以制作JOIN语句以根据需要检索数据。我强烈建议阅读 MySQL 中的多对多关系。


推荐阅读