2012-06-21 77 views
1

好吧,我一直在使用這個工作一段時間,而且我有點卡住了。通過與多個LIKE子句完全匹配的mysql查詢順序

也許我正在做的一切都錯了!

基本上我有一個搜索字段的查詢。總體思路是根據LIKE %%選擇結果,同時仍然首先進行精確匹配。

因此,例如,如果您搜索47我希望47中的任何一個都在id,surname或company_name中顯示,但是如果我鍵入了姓氏,那麼帶有id號47的結果應該在頂部,並且是相同的。

請參閱下面的代碼,這可能有助於澄清我的問題。

SELECT id, 
IF(company_name IS NOT NULL AND company_name <> '', company_name, surname) AS name, 
first_name, country, phone1, isowner, isholidayrenter, isproholidayrenter, 
islongtermrenter, isprolongtermrenter, isprobuyer, isbuyer 
FROM clients 
WHERE id LIKE '$search' OR surname LIKE '$search' OR company_name LIKE '$search' 
union all 
SELECT id, 
IF(company_name IS NOT NULL AND company_name <> '', company_name, surname) AS name,  
first_name, country, phone1, isowner, isholidayrenter, isproholidayrenter,  
islongtermrenter, isprolongtermrenter, isprobuyer, isbuyer 
FROM clients 
WHERE id LIKE '%$search%' AND id NOT LIKE '$search' OR surname LIKE '%$search%' 
and SURNAME NOT LIKE '$search' OR company_name LIKE '%$search%' 
and company_name NOT LIKE '$search' 
LIMIT $start, $limit"; 

`

回答

3

嘗試這種情況:

(選擇精確匹配)聯合所有與(選擇部分匹配省略精確匹配)

(
    SELECT 
     id, 
     IF(company_name IS NOT NULL AND company_name <> '', company_name, surname) AS name, 
     first_name, country, phone1, isowner, isholidayrenter, isproholidayrenter, 
     islongtermrenter, isprolongtermrenter, isprobuyer, isbuyer 
    FROM 
     clients 
    WHERE 
     id LIKE '$search' OR 
     surname LIKE '$search' OR 
     company_name LIKE '$search' 
) 
union all 
(
    SELECT 
     id, 
     IF(company_name IS NOT NULL AND company_name <> '', company_name, surname) AS name, 
     first_name, country, phone1, isowner, isholidayrenter, isproholidayrenter, 
     islongtermrenter, isprolongtermrenter, isprobuyer, isbuyer 
    FROM 
     clients 
    WHERE 
     (id LIKE '%$search%' AND id NOT LIKE '$search') OR 
     (surname LIKE '%$search%' AND SURNAME NOT LIKE '$search') OR 
     (company_name LIKE '%$search%' AND company_name NOT LIKE '$search') 
) 
LIMIT $start, $limit; 
+0

絕對完美,非常感謝。我並不希望將它放在盤子上。 – traxwriter

+0

這是我第一次去做,但我沒有足夠的代表點投票。 :( – traxwriter