我是 SQL 的新手,我试图了解一些基本的东西。
我有 2 个表:
- 用户:ID |姓名 |电子邮件 |应用程序
- 应用:ID |姓名
问题
我如何基于这两个创建第三个表,作为 JSON 将如下所示:
[
{ id: 1, name: 'Daniel', email: 'dan@iel.com', apps: [1,2,3]},
{ id: 2, name: 'Ben', email: 'dan@iel.com', apps: [1,5]},
{ id: 3, name: 'Maya', email: 'dan@iel.com', apps: [4]}
]
明智的查询,我如何编写一个查询来创建这样的用户,其中 apps 是一个 ID 列表:
{ id: 1, name: 'Daniel', email: 'dan@iel.com, apps: [1,2,3]}
最佳答案
使用数据透视表不是更好吗?
数据透视表:
[
{ pivot_id: user_id, app_id },
{ pivot_id: user_id, app_id },
]
可以使用一个简单的循环来插入数据透视表
foreach(apps as app_id)
{
query = "INSERT INTO pivot_table set user_id = `user_id`, app_id = `app_id` ";
}
关于mysql - 如何在 mysql 表上存储多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56766240/