mysql - 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))
解决方案
我将在这里分解几点,这主要是由于您的问题不明确:
第一的
pq.Array
PostgreSQL 中用于将数组值转换为安全列表,如以下语句:
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 中的多对多关系。
推荐阅读
- css - 为什么许多小方块 div 的渲染方式不同?
- ios - 某些操作会导致 MPMusicPlayerApplicationController 因“无法获取播放队列标识符”错误而锁定
- java - 读取行间java的数据
- unit-testing - 如何将 Jest 模拟函数的范围限制为单个测试
- javascript - 如何使用 JavaScript Fetch 发布到 Rails 应用程序
- android - 如果我的应用程序使用的依赖项被修改或删除,我的应用程序会中断吗?
- json - 来自 httpClient 的 POST 错误(HTTP/1.1 500 内部服务器错误)但在 Postman 中有效
- wpf - 如何从文本框 wpf 在数据网格中创建指定数量的列
- ios - ubiquityIdentityToken 在登录 iCloud 时返回值,但在退出 iCloud 后仍返回值
- tensorflow - 如何在 tf.keras 中计算梯度权重并在 tensorboard 上记录梯度监测?