MySQL数据库CSV文件和概念

时间:2012-12-10 10:11:39

标签: database-design csv

我的数据库模型概念有些问题。

我有一个很大的CSV文件用于未来网站的类别。

BIGCAT1;SUBCAT1;SUBSUBCAT1;BRAND1
BIGCAT1;SUBCAT1;SUBSUBCAT2;BRAND2
BIGCAT2;SUBCAT2;SUBSUBCAT3;BRAND1
BIGCAT2;SUBCAT2;SUBSUBCAT4;BRAND3

如您所见,SUBCATx仅适用于BIGCATx。 SUBSUBCATx仅适用于SUBCATx。但BRANDx可以属于多个SUBSUBCAT。

一开始,我创建了一个CSV解析器......我和每个BRAND就像一个sububsub ... cat。它有效,但它是如此令人反感。如果我将每个品牌视为一个类别,我有3,600个品牌......当我删除重复项时,我只有2,106个独特的品牌......(+/- 1,500个重复品牌)。

如果我认为我的数据库模型具有关系类别(id,is_active)/ category_has_brand(category.id,brand.id)/ brand(id,is_active):我如何使用CSV文件生成数据库插入?

因为它很有趣......它是多语言的(对于BIGCAT,SUBCAT,SUBSUBCAT而不是BRAND)。

如果我手动填写这个数据库......没关系。但我不想这样做。

有人有想法吗?我使用PHP和MySQL来读取我的文件并填充我的数据库。

有没有办法使用这种CSV在3个SQL表中生成条目:category(id,is_active)/ category_has_brand(category.id,brand.id)/ brand(id,is_active)?

问候

2 个答案:

答案 0 :(得分:1)

我想你提出两个问题:

  • 我应该如何构建数据库?
  • 我应该如何导入我的CSV文件?

数据库设计非常简单:

Category
-----------
CategoryID
ParentCategoryID

这是基于“子类别仅属于单亲”声明。如果结果是“多对多”,则需要创建一个连接表而不是ParentGategoryID。

要存储本地化的类别描述等,您可以拥有本地化的字符串表:

CategoryDescription
------------
CategoryID
Locale
Description

根据您所写的内容,类别和品牌之间存在“多对多”,因此可以如下工作:

Brand
-----
BrandID
.... 

CategoryBrand
---------
CategoryID
BrandID

我认为没有一种简洁的方法来导入CSV文件。伪代码可能是:

for each line in CSV file
  for each field in line
     if field is category
          add category if not exists
          if category is not top level
              set category Parent to last category
          end if
     end if
     if field is brand
         add brand if not exists
         set brand category to last category
     end if
   next field
 next line

答案 1 :(得分:0)

我会为Cat / Subcat / SubSubcat创建3个表。

CatId | Description | Whatever else fits there, like "active flag".

...

SubCatId | Description | Whatever else fits there, like "active flag".

...

SubSubCatId | Description | Whatever else fits there, like "active flag".

然后是品牌表:

...

BrandId | Name | Description | Whatever else fits there, like "Country Iso Code".

然后我会创建一个“Triplet + Brand”结构,其中包含3个表的前导键:

CatId|SubcatId|SubSubCatId|BrandId

现在您的CSV导入变为:

Read a record from CSV
   Split it into Cat/Subcat/SubSubCat/Brand - these will all be descriptions, or names
   Find if the the Category exists, if yes get ID from DB, otherwise create Category table and generate Id by sequence
   Find SubCategory (as above)
   ...
   Find Brand (as above)
   Create record with  CatId+SubcatId+SubSubCatId+BrandId

使用适当的唯一键,您还可以避免在创建期间或应用程序生命周期的后期重复。<​​/ p>