MySQL:如何转换为 EAV - 第 2 部分?

标签 mysql database database-design entity-attribute-value

这是第 1 部分:MySQL: how to convert to EAV?

现在我也想做一些不同的事情。假设我有下表:

TABLE: one
=======================================
| id | fk_id | attribute  | value     |
=======================================
| 1  | 10    | first_name | John      |
| 2  | 10    | last_name  | Doe       |
| 3  | 55    | first_name | Bob       |
| 4  | 55    | last_name  | Smith     |
---------------------------------------

我想把它转换成这个 EAV 模型:

TABLE: attribute
===================
| id | attribute  |
===================
| 1  | first_name |
| 2  | last_name  |
-------------------

TABLE: value
=====================================
| id | attribute_id | fk_id | value |
=====================================
| 1  | 1            | 10    | John  |
| 2  | 2            | 10    | Doe   |
| 3  | 1            | 55    | Bob   |
| 4  | 2            | 55    | Smith |
-------------------------------------

假设表 attributevalue 已经定义。如何将表 one 中的数据插入到两个目标表中。对我来说,一个大问题是如何使关系 (attribute.id => value.attribute_id) 正确。

最佳答案

INSERT INTO attribute
  (attribute)
SELECT DISTINCT
  attribute
FROM one ;

INSERT INTO value
  (attribute_id, fk_id, value)
SELECT 
  attribute.id, one.fk_id, one.value
FROM one
  JOIN attribute
    ON attribute.attribute = one.attribute ;

关于MySQL:如何转换为 EAV - 第 2 部分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7034212/

相关文章:

mysql - Liquibase 验证异常 : forIndexName is not allowed in mysql

mysql - 如何将这两个sql合并为一个sql?

mongodb - 在 MongoDB 中创建数据库并从文件中插入数据

mysql - 如果数据库中的表被更新或更改,它是否有可能自动转储到 .sql 文件中?

mysql - 跨多个系统转换和同步数据

Mysql 索引和连接

php - 如何使用 php 运行具有多个创建命令的 sql 文件,而无需手动解析 sql 文件?

MySQL查询 "more than one row"

mysql - 表中要保留多少列? - MySQL

sql - 为自定义产品类型定义通用数据模型