2014-02-25 86 views
0

我正在處理一個查詢,該查詢應該按搜索的關鍵字返回大多數匹配的數組或標題。不知道即使查詢是應該的,但它的工作原理。不要擔心注射,我會在稍後處理。這裏的目標是返回結果最多的行的標題。MySQL查詢返回大多數匹配的第一個

$query = "SELECT * "; 
    $query .= "FROM user_rec "; 
    $query .= "WHERE sast1 = '" . $mekletie[0] . "'"; 
    $query .= "OR sast1 = '" . $mekletie[1] . "'"; 
    $query .= "OR sast1 = '" . $mekletie[2] . "'"; 

/*NOTE - the query isn't complete yet, it will run sast2 next and so on until sast5 
and compare all the same searched keywords */ 

$result = mysqli_query($connection, $query); 
    if (!$result) { 
     die ("DB query nedarbojas"); 
    } 
+0

目前尚不清楚是什麼問題,或者你正在試圖完成的任務。 –

回答

0

好像你想這樣做:

$query = 
"SELECT * 
FROM 
    (SELECT 
    u.*, 
    (sast1 = '" . $mekletie[0] . "' + 
     sast1 = '" . $mekletie[1] . "' + 
     sast1 = '" . $mekletie[2] . "' + 
     sast2 = '" . $mekletie[0] . "' + 
     sast2 = '" . $mekletie[1] . "' + 
     sast2 = '" . $mekletie[2] . "') AS numberofmatches 
    FROM user_rec) m 
WHERE 
    m.numberofmatches > 0 
ORDER BY 
    m.numberofmatches DESC"; 

但它不會工作,因爲如果sast1比賽$mekletie[0]那麼它不會匹配$mekletie[1],除非它們是相同的,但那麼它首先不是很有用。

我看到您的評論,指出還有一個stat2。在這種情況下,您可以使用這種方法。但是,如果你是存儲關鍵字的用戶,你可能要考慮的關鍵字一個單獨的表,你可以加入這樣的:

$query = 
"SELECT 
    u.* 
FROM 
    user_rec u 
    -- Inner join implicitly excludes users that don't have any matching tag. 
    INNER JOIN user_tag t ON t.userid = u.userid 
WHERE 
    t.tag IN ('" .$mekletie[0] . "', '" . $mekletie[1] . "', '" . $mekletie[2] . "') 
GROUP BY 
    -- Mysql, unlike other databases, allows you to specify only the id 
    -- in group by when actually returning other fields as well. 
    u.userid 
ORDER BY 
    -- You can return the count, or use it just for sorting. 
    COUNT(t.userid) DESC" 
+0

如果任何$ mekletie匹配sast1我們跳轉到sast 2並繼續查詢 – slc

+0

是的,我做了一個改變,表明這一點。 – GolezTrol

+0

太棒了!謝謝 – slc