mySQL查询 - 简单的数学问题

时间:2012-07-02 11:54:08

标签: php mysql pdo

每个人都有2个电话号码。其中一些只有电话填写其他人只有电话2填写,一些有两个。

我试图找到其他人使用相同的电话号码,电话=电话,电话=电话2,电话2 =电话,电话2 =电话2

问题是,如果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);
            }

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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);
        }