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

发布于 2024-11-29 07:57:38 字数 1195 浏览 2 评论 0原文

这是第 1 部分: MySQL:如何转换为 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)。

Here's Part 1: MySQL: how to convert to EAV?

Now I want to also do something different. Say I have the following table:

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     |
---------------------------------------

I want to convert it to this EAV model:

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 |
-------------------------------------

Assume the tables attribute and value are already defined. How do I insert the data from table one into the two target tables. One big problem for me is how to get the relationship (attribute.id => value.attribute_id) right.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

缪败 2024-12-06 07:57:38
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 ;
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 ;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文