【发布时间】:2015-01-13 21:11:07
【问题描述】:
为使用 SQL 的用户查找推荐产品
我有一个产品目录。
例如: 名称:产品1 城市:整数(表格城市中城市的 ID) 产品特征:整数数组(每个整数 - 表特征中产品特征的id)
Table products:
id name city
1 Product 1 5
Table product_features:
id product_id feature_id
1 1 2
2 1 3
3 1 5
Table features:
id title
2 Mobile
3 Fast
5 External power source
某些注册用户 (id=10) 在网站上执行搜索。用户搜索(使用复选框或其他任何东西)
示例:来自城市 5 的产品,具有功能 3(移动)和 5(外部电源)
搜索存储在表 user_searches 中:
id user_id search_city search_features (string - list of needed features divided by ",")
1 10 5 3,5
2 11 5 2
2 12 7 3,5
2 13 5 5
例子:
稍后新产品添加到目录中。我需要找到需要通知此产品的用户 如果产品功能与用户搜索匹配
示例:新产品。
id name city
2 Product 2(new) 5
product_features:
id product_id feature_id
5 2 3
6 2 5
应该通知一些用户有关此产品的信息
表用户搜索:
id user_id search_city search_features
1 10 5 3,5 (should be notified - new product city:5, features:3,5 )
2 11 5 2 (shouldn't be notified - user needs only feature #2)
2 12 7 3,5 (shouldn't be notified - user searched in another city)
2 13 5 5 (should be notified - user needs feature #5 - new product has this feature )
我尝试使用带有“IN”运算符的 SQL 查询来获取需要通知的用户数组 但当用户搜索多个功能时,它并不能解决任务:
例子:
product_features user_searched
3,5 3
3 IN 3, 5 - 工作
product_features user_searched
3,5,10,20 3,5,7,2
3、5、10、20 IN 3、5、7、2....当然不行
我还尝试将每个用户需要的功能存储在另一个表中 (每行 1 个特征 ID)
user_id feature_id
10 3
10 5
11 3
等等……
但是得到了同样的错误结果。我的任何其他想法看起来都比以前更愚蠢。
因此,如果他们搜索类似的产品,我需要获取需要通知新产品的用户数组...我认为应该有更简单的解决方案但找不到。
有什么想法吗...?
【问题讨论】:
-
您使用的是哪个 DBMS?后格雷斯?甲骨文?
-
user_searches 中每个用户是否只有一行?或者它就像一个历史表?
-
在 MySQL 中,您有 FIND_IN_SET 函数来搜索包含逗号分隔列表的字符串中的元素。因此,您不需要用于搜索功能的表格。如果您想要一个更标准的解决方案,那么这样的表格将是合适的。但是,它不会包含 user_id + feature_id,而是 user_search_id + feature_id。