假设用户有一个搜索表单,他可以在其中搜索属性。假设他选择:
地点:ABC 价格范围:100万-500万 卧室数量范围:5 - 12 状态 : XYZ 县 : PQR 类别:移动网络运营商
匹配他选择的所有字段以从数据库中产生结果的机会非常小。所以AND
在WHERE
这里使用条件似乎并不有效。我想要的是——
- 如果所有选择都匹配,那么没有问题显示结果
- 如果位置、价格范围、状态匹配,则也显示结果
- 如果位置、卧室数量、类别、状态匹配,则也显示结果
- 依此类推....如果任何组合匹配,则显示结果
如何过滤表中与任何搜索词匹配的记录并按匹配词数的降序对结果进行排序:
SELECT *,
(Location = 'ABC')
+ (Price BETWEEN 1000000 AND 5000000)
+ (Bedrooms BETWEEN 5 AND 12)
+ (State = 'XYZ')
+ (County = 'PQR')
+ (Category = 'MNO')
AS relevance
FROM my_table
WHERE (Location = 'ABC')
OR (Price BETWEEN 1000000 AND 5000000)
OR (Bedrooms BETWEEN 5 AND 12)
OR (State = 'XYZ')
OR (County = 'PQR')
OR (Category = 'MNO')
HAVING relevance >= ? -- specify the minimum number of matching terms here
ORDER BY relevance DESC
LIMIT ? -- specify the maximum number of matching records here
您可能希望在 WHERE 子句中设置多个条件
WHERE (Location AND price AND Bedrooms AND State AND County AND Category)
OR (Location AND Price AND State)
OR (Location AND Bedrooms AND Category AND State)
OR (...)
...
这允许您希望有效的任何数据组合返回数据。
类似于 eggyals 解决方案,但只是带回您关心的行。未经测试,请原谅任何错别字:-
SELECT Sub2.*
FROM (SELECT MAX(
CASE WHEN Location = 'ABC' THEN 1 ELSE 0 END +
CASE WHEN Price BETWEEN 1000000 AND 5000000 THEN 1 ELSE 0 END +
CASE WHEN Bedrooms BETWEEN 5 AND 12 THEN 1 ELSE 0 END +
CASE WHEN State = 'XYZ' THEN 1 ELSE 0 END +
CASE WHEN County = 'PQR' THEN 1 ELSE 0 END +
CASE WHEN Category = 'MNO' THEN 1 ELSE 0 END) AS MatchCount
FROM my_table a
WHERE (Location = 'ABC')
OR (Price BETWEEN 1000000 AND 5000000)
OR (Bedrooms BETWEEN 5 AND 12)
OR (State = 'XYZ')
OR (County = 'PQR')
OR (Category = 'MNO'))Sub1
INNER JOIN (SELECT a.*,
CASE WHEN Location = 'ABC' THEN 1 ELSE 0 END +
CASE WHEN Price BETWEEN 1000000 AND 5000000 THEN 1 ELSE 0 END +
CASE WHEN Bedrooms BETWEEN 5 AND 12 THEN 1 ELSE 0 END +
CASE WHEN State = 'XYZ' THEN 1 ELSE 0 END +
CASE WHEN County = 'PQR' THEN 1 ELSE 0 END +
CASE WHEN Category = 'MNO' THEN 1 ELSE 0 END AS MatchCount
FROM my_table a
WHERE (Location = 'ABC')
OR (Price BETWEEN 1000000 AND 5000000)
OR (Bedrooms BETWEEN 5 AND 12)
OR (State = 'XYZ')
OR (County = 'PQR')
OR (Category = 'MNO')) Sub2
ON Sub1.MatchCount = Sub2.MatchCount