2012-07-02 92 views
0

我有2個電話號碼爲每個人。其中有些人只有電話填寫其他人只有電話2填寫,有些人都有。mySQL查詢 - 簡單的數學問題

我試圖找其他人用同一個電話號碼,無論是電話=電話,電話= telephone2,telephone2 =電話,telephone2 = telephone2

問題是,如果telephone1爲空,然後我現有的代碼將如果電話或電話2爲空,則將其與具有電話號碼的下一個人相匹配,而不管匹配如何。我需要添加什麼代碼。

function getothers($tid,$criteria,$telephone,$telephone2,$elector){ 
       global $dbh; 
       $tid = '-TID'.$tid; 
       $sql = "SELECT * FROM electors 
WHERE (telephone > 0 OR telephone2 > 0) 
AND records NOT RLIKE '$tid' 
AND (telephone IN ('$telephone','$telephone2') 
OR telephone2 IN ('$telephone','$telephone2')) 
AND ID != '$elector' LIMIT 10"; 
       return $dbh->query($sql); 
      } 
+0

嘗試使用IS NOT NULL?或從字段定義中刪除NULL – Waygood

+0

電話> 0意味着您將它們存儲爲數字。這是一個壞主意。 003531111是電話「號碼」,3531111是不一樣的。 – Waygood

回答

1
SELECT T_el.* 
FROM (electors AS T_el) LEFT JOIN (electors AS T_dup) 
ON (T_el.ID!=T_dup.ID 
    AND (
    (T_el.telephone IS NOT NULL AND (T_el.telephone=T_dup.telephone OR T_el.telephone=T_dup.telephone2)) 
    OR 
    (T_el.telephone2 IS NOT NULL AND (T_el.telephone2=T_dup.telephone OR T_el.telephone2=T_dup.telephone2)) 
    ) 
) 
WHERE T_dup.ID IS NOT NULL 
GROUP BY T_el.ID 
0
function getothers($tid,$criteria,$telephone,$telephone2,$elector){ 
      global $dbh; 
      $tid = '-TID'.$tid; 
      $sql = "SELECT * FROM electors WHERE (telephone > 0 AND telephone IN ('$telephone','$telephone2')) OR (telephone2 > 0 AND telephone2 IN ('$telephone','$telephone2')) $criteria AND records NOT RLIKE '$tid' AND ID != '$elector' LIMIT 10"; 
      return $dbh->query($sql); 
     }