複数のカテゴリのアイテムを追加する Web サイトを構築しています。
複数のカテゴリを 1 つのフィールドに格納し、フィールドを検索可能にしておく最善の方法は何ですか?
複数のカテゴリのアイテムを追加する Web サイトを構築しています。
複数のカテゴリを 1 つのフィールドに格納し、フィールドを検索可能にしておく最善の方法は何ですか?
1つのフィールドに複数のカテゴリを保存するのではなく、各アイテムにカテゴリを割り当てるための個別のテーブルを作成します。これに似ています:
-- create your table to store items/products
create table items
(
id int, -- this will be the PK
name varchar(10)
);
insert into items values
(1, 'product1'),
(2, 'product2');
-- create your table to store categories
create table categories
(
id int, -- this will be the PK
name varchar(50)
);
insert into categories values
(1, 'color'),
(3, 'material'),
(6, 'size');
-- create your join table to assign the categories to each item
-- this table will have a foreign key relationship to the items and categories table
create table items_categories
(
item_id int, -- both fields will be the PK
category_id int
);
insert into items_categories values
(1, 1),
(2, 3),
(2, 6);
次に、テーブルを結合してデータをクエリします。
select i.id itemid,
i.name item,
c.name category
from items i
left join items_categories ic
on i.id = ic.item_id
left join categories c
on ic.category_id = c.id
SQL FiddleWithDemoを参照してください
最善の方法は、「1つのフィールドに複数のカテゴリを格納する」ことではありません。
代わりに、ItemCategories用に別のテーブルを用意してください。
データベースの正規化と内部ダイジェストについて読んでください。
item-category
カテゴリIDとアイテムIDを格納するようなリレーションシップテーブルを作成できます。次に、検索クエリをリレーションシップテーブルに直接配置できます。独自の主キーもあることを確認してください。
すべてのカテゴリを1つのファイルに保存しようとしないでください。これが「関係テーブル」の目的であり、次のようなテーブルを作成する必要があります。
product_categories (
`id` INT AUTO_INCREMENT,
`product_id` INT NOT NULL,
`category_id` INT NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY (`product_id`, `category_id`)
)
FOREIGN KEY
このようにして、変更や削除などを処理するものを追加することもできます。
1つのエントリに別々のアイテムを保存することはめったに良い考えではありません。
ただし、それを本当に主張する場合は、たとえば、を使用して、配列として格納した可能性のあるカテゴリをシリアル化するのがおそらく最善ですjson_serialize
。次に、sqlsLIKE
演算子を使用してデータベースを検索します。