我想创建表'field_value'的条目,该表包含表'field'的外键,因为许多列都会产生自定义列名。
让我解释一个例子: 表'field_value'包含值:
+---------------------+
| field_value |
+---------------------+
|v_value v_id |
| Peter 1 |
| Lagaf 2 |
| Football 3 |
| Male 4 |
| 12345678 5 |
+---------------------+
表格字段将包含指定的列
+--------------------+
| field |
+--------------------+
| f_id f_label |
| 1 surname |
| 2 name |
| 3 hobbies |
| 4 sex |
| 5 phone |
+--------------------+
结果如下:
+---------------------------------------------+
| Result |
+---------------------------------------------+
| surname name hobbies sex phone |
| Peter Lagaf Football Male 12345678 |
+---------------------------------------------+
答案 0 :(得分:0)
您的数据库未规范化 - 如果不知道规范化架构应该是什么样子,则无法给出确定的答案。此外,您的架构无法容纳多个记录。您的问题最重要的问题是,没有任何内容可以将构成记录的字段值组合在一起,您没有说明每个记录的唯一标识符是什么,也不是每个“记录”都有完整的field_value表中的属性集。
考虑一下数据库中有多个记录的情况 - 我们怎么知道电话号码12345678与姓氏彼此有关,而不是保罗。
最简单的解决方案(从静态数据的角度来看)是将记录标识符的属性添加到字段表中:
SELECT record.value, surname.value, name.value, hobbies.value....
FROM field AS record
INNER JOIN field AS surname
ON record.record_id=surname.record_id
AND surname.f_id=1
INNER JOIN field AS name
ON record.record_id=name.record_id
AND name.f_id=2
INNER JOIN field AS hobbies
ON record.record_id=hobbies.record_id
AND hobbies.f_id=3
...
WHERE record.f_id=0
ON record.record_id=name.record_id
答案 1 :(得分:0)
感谢symcbean的回复。
我想简化帖子,这是真正的表格和真实的结果: 我想显示具有collect_id = 2的订单商品 我想显示与每个order_item相关的所有字段。
+-------------------------------+
| order_item |
+-------------------------------+
| oi_id oi_price oi_collect_id |
| 1 100 2 |
| 2 30 2 |
| 3 55 3 |
| 4 70 4 |
| 5 220 2 |
| 6 300 4 |
+-------------------------------+
+-----------------------------------+
| field_value |
+-----------------------------------+
| v_value v_fk_field_id oi_fk_id |
| Peter 1 1 |
| Lagaf 2 1 |
| Football 3 1 |
| Male 4 1 |
| 12345678 5 1 |
| Frank 1 2 |
| Loran 2 2 |
| Tennis 3 2 |
| Male 4 2 |
| 11223658 5 2 |
| Nathali 1 3 |
| Waton 2 3 |
| Reading 3 3 |
+-----------------------------------+
oi_fk_id : foreign key ref(order_item.oi_id)
v_fk_field_id : foreign key ref(field.f_id)
+--------------------+
| field |
+--------------------+
| f_id f_label |
| 1 surname |
| 2 name |
| 3 hobbies |
| 4 sex |
| 5 phone |
+--------------------+
+-----------------------------------------------------------------------------+
| Result |
+-----------------------------------------------------------------------------+
| oi_id oi_price oi_collect_id surname name hobbies sex phone |
| 1 100 2 Peter Lagaf Football Male 12345678 |
| 2 30 2 Frank Loran Tennis Male 11223658 |
| 5 220 2 Nathali Waton Reading null null |
+-----------------------------------------------------------------------------+
重要提示:表格字段不仅包含这5个字段(名称,姓氏,爱好,性别,电话),但它可以包含许多其他字段,开发人员可能不知道,对于表格上的对应值也是如此'FIELD_VALUE'