2017-08-06 16 views
0

我想基於搜索查詢顯示行。 但是,我有3個表,並希望在所有3中搜索,如果某事是LIKE('%$ parameter%')參數。如何從3個喜歡的表中選擇

這是我當前的代碼:

SELECT a.Name as aName 
    , b.Name as bName 
    , c.Name as cName 
    FROM TableA a 
    , TableB b 
    , TableC c 
WHERE a.Name LIKE '%$parameter%' 
    OR b.Name LIKE '%$parameter%' 
    OR c.Name LIKE '%$parameter%' 

而在PHP我做了以下內容:

if($row['aName'] != ""){ echo $row['aName']; } 
if($row['bName'] != ""){ echo $row['bName']; } 
if($row['cName'] != ""){ echo $row['cName']; } 

但是這...只是拋出每一行的所有表,即使他們甚至不匹配參數。

我在google或者stackoverflow上找不到任何有幫助的東西。

請幫忙!

+0

'$ parameter'的值是什麼? – Ali

+0

@Ali $參數是我在搜索輸入中輸入的內容,無所謂我放在...表中的字符串或一些無意義的字符串,它仍然顯示27.000結果,3表只有大約5.000排在一起 – David

+0

'var_dump($參數)'來檢查它是否不爲空 – Ali

回答

1

您應該更新您的SQL因此它不會回到3列,但1列,這也將簡化你的php一點:

SELECT a.Name as aName 
    FROM TableA a 
    WHERE a.Name LIKE '%$parameter%' 
union 
    SELECT b.Name as bName 
    FROM TableB b 
    WHERE b.Name LIKE '%$parameter%' 
union 
    SELECT c.Name as cName 
    FROM TableC c 
    WHERE c.Name LIKE '%$parameter%' 

這樣你就只能得到匹配的線,你會救自己免受不必要的全笛卡爾積3個表之間。

+0

修復它,謝謝! – David

1

沒有爲加入你的表,你只是做一個笛卡爾乘積(稱爲Cross Join)任何條件,所以你需要添加加盟條件表到對方:

SELECT a.Name as aName 
    , b.Name as bName 
    , c.Name as cName 
    FROM TableA a 
    INNER JOIN TableB b 
     a.name = b.name /* they are should have the same data for matching OR if it's OK then you can use your "Primary Key Columns" for matching other tables*/ 
    INNER JOIN TableC c 
     ON a.name = c.name 
    WHERE 
     a.Name LIKE '%$parameter%' 
     OR b.Name LIKE '%$parameter%' 
     OR c.Name LIKE '%$parameter%';