假设用户有一个搜索表单,他搜索属性。让我们说他选择:
Location : ABC Price Range : 1 million - 5 millions No. of Bedrooms Range : 5 - 12 State : XYZ County : PQR Category: MNO
很有可能匹配他选择的所有字段以从数据库中产生结果。所以在AND
条件下使用WHERE
在这里似乎没有效果。我想要的是 -
答案 0 :(得分:3)
您希望在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 (...)
...
这允许您希望有效的任何数据组合返回数据。
答案 1 :(得分:3)
如何过滤表格以查找与任何搜索字词匹配的记录,并按匹配字词数量的降序对结果进行排序:
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
答案 2 :(得分:2)
与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