复杂的SQL查询JOIN和WHERE

时间:2013-05-09 15:20:35

标签: php mysql sql codeigniter join

我有一张桌子,我需要从中获取联系人。所以我使用复杂的查询从我的“短信”表中检索所有联系人。

但是,它应该只计算所提供的“imei”字段的记录,但我的查询会一直返回特定联系人的所有计数。

以下是代码使用:

$sql = $this->db->query('
    SELECT 
        t1.mnumber AS t1_number, t1.mcontent AS t1_content, t1.mcontact as t1_contact, SUM(t2.TOTAL) AS mTotal
    FROM
        sms t1
            JOIN
        (SELECT 
            mContent, mcontact, COUNT(mNumber) AS TOTAL, mnumber, MAX(mID) mID
        FROM
            sms
        GROUP BY mContact) t2 ON t1.mcontact = t2.mcontact
            AND t1.mid = t2.mid
        WHERE t1.mIMEI = ' . (IMEI) . '
        GROUP BY t1.mContact
        ORDER BY t1.mid DESC');

    return $sql->result();

3 个答案:

答案 0 :(得分:2)

格式更好,查询是:

SELECT t1.mnumber AS t1_number, t1.mcontent AS t1_content, t1.mcontact as t1_contact, SUM(t2.TOTAL) AS mTotal
FROM sms t1 JOIN
     (SELECT mContent, mcontact, COUNT(mNumber) AS TOTAL, mnumber, MAX(mID) mID
      FROM sms
      GROUP BY mContact
     ) t2
     ON t1.mcontact = t2.mcontact AND t1.mid = t2.mid
WHERE t1.mIMEI = ' . (IMEI) . '
GROUP BY t1.mContact
ORDER BY t1.mid DESC

问题是where子句位于错误的位置。要使它影响计数,您需要在子查询中使用它。要使它影响输出行,您需要在外部查询中使用它。我建议:

SELECT t1.mnumber AS t1_number, t1.mcontent AS t1_content, t1.mcontact as t1_contact, SUM(t2.TOTAL) AS mTotal
FROM sms t1 JOIN
     (SELECT mContent, mcontact, COUNT(mNumber) AS TOTAL, mnumber, MAX(mID) as maxmid
      FROM sms
      WHERE sms.mIMEI = ' . (IMEI) . '
      GROUP BY mContact
     ) t2
     ON t1.mcontact = t2.mcontact AND t1.mid = t2.maxmid
GROUP BY t1.mContact
ORDER BY t1.mid DESC

我怀疑可能还有其他简化,具体取决于midmcontact在数据库结构方面的含义。

答案 1 :(得分:0)

您需要WHERE两个语句中的SELECT子句。

SELECT t1.mnumber AS t1_number, t1.mcontent AS t1_content, t1.mcontact as t1_contact, SUM(t2.TOTAL) AS mTotal
FROM sms t1 JOIN
     (SELECT mContent, mcontact, COUNT(mNumber) AS TOTAL, mnumber, MAX(mID) mID
      FROM sms
      WHERE mIMEI = ' . (IMEI) . '
      GROUP BY mContact
     ) t2
     ON t1.mcontact = t2.mcontact AND t1.mid = t2.mid
WHERE t1.mIMEI = ' . (IMEI) . '
GROUP BY t1.mContact
ORDER BY t1.mid DESC

如果两个地方都没有WHERE子句,您将加入与mContact匹配的所有记录。即使是那些不符合t1.mIMEI = ' . (IMEI) . '条件的人。

答案 2 :(得分:0)

@Gordon Linoff给出的答案是正确的。 真正的问题是表格本身。

它存储所有消息,但有时“mNumber”是国际电话号码,有时它是用户将其存储到手机中的格式。

因此,当我使用'mNumber'字段加载'mContent'时,它只给我一个部分结果!!

那么还在寻找解决方案吗?也许是多个WHERE clausule?