这是相当简单的,但你可以使用IFNULL()
(MySQL的,或者你的数据库的当量)返回匹配的总和和使用,在您的ORDER BY
// columns and weighting score
$types = array("oranges"=>1, "apples"=>1, "bananas"=>1, "pears"=>1);
$where = array();
// loop through the columns
foreach ($types as $key=>&$weight){
// if there is a match in $_REQUEST at it to $where and increase the weight
if (isset($_REQUEST[$key])){
$where[] = $key . " = 1";
$weight = 2;
}
}
// build the WHERE clause
$where_str = (count($where)>0)? "WHERE " . implode(" OR ", $where) : "";
// build the SQL - non-null matches from the WHERE will be weighted higher
$sql = "SELECT apples, oranges, pears, bananas, ";
foreach ($types as $key=>$weight){
$sql .= "IFNULL({$key}, 0, {$weight}) + ";
}
$sql .= "0 AS score FROM `table` {$where_str} ORDER BY score DESC";
假设“橙子”和“苹果”的选择,你的SQL将是:
SELECT apples, oranges, pears, bananas,
IFNULL(apples, 0, 2) + IFNULL(oranges, 0, 2) + IFNULL(pears, 0, 1) + IFNULL(bananas, 0, 1) + 0 AS score
FROM `table`
WHERE oranges = 1 OR apples = 1
ORDER BY score DESC
不知道我是否理解正确,但如果我这样做只是''ORDER BY orances DESC,pears DESC,bananas DESC'' – Tim
该表可以在这些列中包含1或NULL以外的值吗?如果一场比赛被认为是积极的,那么一场不匹配会被认为是否定的?你想将NULL视为匹配所有内容还是不匹配?也许这意味着UNKNOWN,也许意味着MISSING? – MatBailie
为我的目的是空的有效0。我正在尝试做一个二进制系统。如果该列已被标记,则为1;如果该列尚未标记,则为null。我的意图是没有空值唤起怀疑或没有。 – user1789907