【发布时间】:2015-06-26 06:42:03
【问题描述】:
我需要一个网站上的搜索功能,除此之外,您应该能够选择多个类别。搜索将存储在数据库中,但搜索参数的每个唯一组合只能存储一次,这也包括所选类别的唯一组合。
问题是我不知道如何存储所选类别的组合。我查看了数组并找到了这个http://blog.2ndquadrant.com/postgresql-9-3-development-array-element-foreign-keys/,但显然该功能从未实现过。
因此,如果我需要使用多个表,我想我可以为组合创建一个表,其中每个唯一组合都有一个 id,可以轻松引用和比较,然后另一个表将类别链接到组合。但是通过这种方法,我如何检查组合是否已经存在?我能想到的唯一方法是遍历所有现有组合并检查其中是否有任何一个等于比较组合。
我觉得这不是一个不常见的问题,但我找不到任何这样做的例子。我也觉得我的方法可能不是最好的。非常欢迎任何建议。
I have these two tables currently:
Categories
- CategoryId (int)
- Name (string)
Searches
- SearchId (int)
- Keywords (string)
- ExampleOption1 (bool)
- ExampleOption2 (bool)
- CategoriesCombinationId (int) -- this would represent the unique combination of categories and links to the combination table
这就是我可能尝试解决问题的方法(如果有一种好方法可以检查组合是否已经存在):
CategoriesCombinations -- unique combinations
- CombinationId (int)
CombinedCategories
- CombinationId (int) -- links to id in combinations table
- CategoryId (int) -- links to id in categories table
【问题讨论】:
-
组合中的绝对最大数量类别是多少?请问你的 Postgres 版本是什么?
-
@Erwin Brandstetter Postgresql 9.4,确实没有最大数量,但目前大约有 200 个类别,所以这些类别的任何可能组合。
-
每个组合内中的类别是否唯一? (
'{1,1,1,3,5}'是否允许? -
是的,每个类别在每个组合中只能存在一次。
标签: sql arrays postgresql database-design unique-constraint