這是相當簡單的,但你可以使用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