我有下表存储系统中用户的偏好
UserId | Product | Brand | City |
-------------------------------------------
A | Soap | Tide | NYC |
A | Cereal | Dont-care | NYC |
B | Dont-Care | Tide | Dont-care |
C | Shampoo | Dont-care | Dont-Care |
我想根据用户提供的搜索值来搜索它。所以如果一个人搜索
City: NYC, Brand: Tide
输出应该是:
A | Soap | Tide | NYC |
B | Dont-Care | Tide | Dont-care |
好像他们在哪里寻找
Brand: Tide, Product: Soap
结果应该是:
A | Soap | Tide | NYC |
我目前的解决方案是针对 MySQL 表的以下查询(其中 null 表示“不关心”):
select *
from user_preferences
where (product is null or product = <user provided value>)
and (brand is null or brand = <user provided value>)
and (city is null or city = <user provided value>)
虽然它按预期工作,但 [and + (or)] 组合让我认为这不是正确的方法。我也相当肯定,一旦数据集增加,查询将不会执行良好。
存储和检索此类数据的最有效方法是什么?是否有任何 no-sql 类型的方法可以用来提高效率?
更新
经过一番谷歌搜索后,我认为我所采用的方法可能是最安全的选择。我仍然对这种方法感到矛盾的一个因素是,添加另一个“可搜索”属性将意味着添加一个新列。
这个关于EAV 反模式的博客提供了一些关于这种方案的很好的阅读材料。另请参阅friend-feed 如何使用 MySQL将变量属性存储在表中。