2012-11-18 65 views
2

我試圖避免在我必須允許用戶創建,修改和刪除表字段的項目中出現反模式。所以我正在尋找在表格中存儲JSON數據。例如,我有表產品:在mysql表中存儲和查詢json

Products 
---------------- 
id, 
user_id, 
created, 
modified, 
price, 
_custom <-- there will be stored additional columns for each product needs 
     {"adjustment":0.13, "weight":14.60, "have_some_individual_label":"value"} 

,但我看不出它如何可能包括在查詢_column參數。例如,如何查詢所有產品user_id = 1have_some_individual_label = value。第二個參數可以是一個,多一個(它將用於過濾器和分析)。如果這是不好的方法 - 哪一個更好?謝謝!

回答

1

如果這是不好的方法 - 什麼會更好?

Entity–attribute–value model模型:

CREATE TABLE `ProductInfo` (
    `ProductID` BIGINT UNSIGNED NOT NULL, 
    `AttributeKey` VARCHAR(20) NOT NULL, 
    `AttributeVal` VARCHAR(20), 
    PRIMARY KEY (`ProductID`, `AttributeKey`), 
    FOREIGN KEY (`ProductID`) REFERENCES `Products` (`id`) 
); 

INSERT INTO ProductInfo 
    (`ProductID`, `AttributeKey`    , `AttributeVal`) 
VALUES 
    (  1 , 'adjustment'    ,   '0.13'), 
    (  1 , 'weight'     ,  '14.60'), 
    (  1 , 'have_some_individual_label',  'value') 
; 
0

您提出的JSON方法可能的情況下,你只是想比較等效可用。我寧願建議將多餘的單獨屬性存儲在單獨的表中,並通過其ID將其鏈接到Products表。

CREATE TABLE custom_attrs(prodID int, customAttr varchar(32), 
     customValue varchar(32)); 

這可能是一個更好的方法,儘管它會給表格帶來一些複雜性。