2012-10-31 68 views
3

我在寫一個搜索功能,需要查詢4個表。通過多個表的PHP搜索功能

  • 用戶
  • 類型
  • 亞型
  • 提供的服務

我需要運行通過users表基於各自id搜索,其中查詢typessubtypesservices offered在用戶表中。

例如:

在用戶表中的一行可以是這樣的:

| id | type | subtype | services_offered | first_name | last_name | contact | company | 
| 1 | 1 | 2 |  47  | Gareth  | Davies | [email protected] | Gazza | 

在類型表中的一行可以是這樣的:

​​

等等...

我有它的工作,但由於某種原因,它返回約30行每聯繫!這是我的SQL。

SELECT 
    c.type, c.subtype, c.first_name, c.last_name, c.company, c.contact, c.services_provided, c.additional_information, c.date_updated, t.id, t.type, s.id, s.subtype, so.id, so.services_offered 
FROM 
    contacts c, types t, subtypes s, services_offered so 
WHERE 
    ((c.type LIKE '%$q%' || c.subtype LIKE '%$q%' || c.first_name LIKE '%$q%' || c.last_name LIKE '%$q%' || c.company LIKE '%$q%' || c.services_provided LIKE '%$q%' || c.contact LIKE '%$q%' || c.additional_information LIKE '%$q%' || t.type LIKE '%$q%' || s.subtype LIKE '%$q%' || so.services_offered LIKE '%$q%') 
    AND (c.type = t.id || c.subtype = s.id || c.services_provided = so.id)) 

理想情況下,它只會返回每個聯繫人之一!

任何幫助將不勝感激!

感謝,

回答

0

一個合理的猜測是,你需要組的結果,所以使用

GROUP BY c.id 

查詢的結束可能會做它

+0

真棒!謝謝! – daviesgo

+0

@daviesgo偉大的工作!請將問題標記爲已解決! – jtheman