使用WHERE IN后我的SQL JOIN语句出现问题

时间:2018-04-08 13:53:29

标签: mysql

SELECT contactid, firstname, email, phone
FROM vtiger_contactscf t1
WHERE email
IN (SELECT email FROM vtiger_contactscf WHERE CHAR_LENGTH(email)>0 GROUP BY email HAVING count(*)>1)
OR phone
IN (SELECT phone FROM vtiger_contactscf WHERE CHAR_LENGTH(phone)>0 GROUP BY phone HAVING count(*)>1)

上述SQL查询生成一个表格,其中包含我拥有的所有联系人,这些联系人与另一个联系人具有相同的电子邮件或电话号码。

对于每个联系人,我都会收到contactid,firstname,phone和email。但是,我也想加入姓氏。但是姓氏数据存储在不同的表中。该表也有contactid所以我可以用它来JOIN ON。但是,当我只添加一个JOIN t2 ON t1.contactid=t2.contactid时,它仍然无效。

使用join语句的完整代码:

SELECT t1.contactid, t1.firstname, t2.lastname t1.email, t1.phone
FROM vtiger_contactscf t1
WHERE t1.email
IN (SELECT email FROM vtiger_contactscf WHERE CHAR_LENGTH(email)>0 GROUP BY email HAVING count(*)>1)
OR t1.phone
IN (SELECT phone FROM vtiger_contactscf WHERE CHAR_LENGTH(phone)>0 GROUP BY phone HAVING count(*)>1)
JOIN vtiger_contactsdetails t2 ON t1.contactid = t2.contactid

我做错了什么?

1 个答案:

答案 0 :(得分:2)

JOIN是属于FROM子句的运算符:

SELECT c.contactid, c.firstname, cd.lastname c.email, c.phone
FROM vtiger_contactscf c JOIN
     vtiger_contactsdetails cd
     ON c.contactid = cd.contactid
WHERE c.email IN (SELECT c2.email
                  FROM vtiger_contactscf c2
                  WHERE CHAR_LENGTH(c2.email) > 0
                  GROUP BY c2.email
                  HAVING count(*) > 1
                 ) OR
      c.phone IN (SELECT c2.phone
                  FROM vtiger_contactscf c2
                  WHERE CHAR_LENGTH(c2.phone) > 0
                  GROUP BY phone
                  HAVING count(*) > 1
                 );

那说,这看起来有点奇怪。你有两个基本相同的主键表?一个contactid可能在详细信息表中有多行吗?如果是这样,上述逻辑可能不起作用,因为多个记录可能具有相同的电话号码或电子邮件。

您可以使用EXISTS修正此问题并简化查询:

SELECT c.contactid, c.firstname, cd.lastname c.email, c.phone
FROM vtiger_contactscf c JOIN
     vtiger_contactsdetails cd
     ON c.contactid = cd.contactid
WHERE EXISTS (SELECT 1
              FROM vtiger_contactscf c2
              WHERE CHAR_LENGTH(c2.email) > 0 AND c2.email = c.email AND c2.contactid <> c.contactid
             ) OR
      EXISTS (SELECT c2.phone
              FROM vtiger_contactscf c2
              WHERE CHAR_LENGTH(c2.phone) > 0 AND c2.phone = c.phone AND c2.contactid <> c.contactid
             );

这可能看起来不那么简单,但EXISTS可以利用vtiger_contactscf(phone, contactid)vtiger_contactscf(email, contactid)上的索引。