3表左外连接不适用于子查询

时间:2011-07-16 01:51:25

标签: php mysql

简要说明......我有4张桌子。 “联系人”(每个人的列表,唯一ID),contact_phones(每个联系人的多个电话号码,contact_id上的联接)和contact_communication(每次我们与此联系人交谈,加入contact_id时)和学校(a学校名单,加入学校.school_id = contacts.contact_id)。

我需要什么:我需要找一所学校。对于那所学校,我需要一份每个人的名单,他们的主要电话号码,以及我们与他们的最后一次沟通(如果有的话)。

问题是,如果我们没有与他们沟通,他们就不会出现在列表中。如果我在“WHERE”子句中取出“AND”语句,那么我会获得多个通信记录。我只想要最新的通讯记录,但我想要所有联系人。但有些联系人没有通讯记录。

这是我的疑问:

SELECT c.id,
            c.f_name,
            c.l_name,
            c.address1,
            c.address2,
            c.city,
            c.state,
            c.zip,
            c.tel,
            c.school_id,
            c.email,
                ct.tel,
                cc.date,
                cc.reason,
                cc.result,
                cc.caller
                FROM contacts AS c
                LEFT OUTER JOIN contact_phones AS ct ON c.id = ct.contact_id
                LEFT OUTER JOIN contact_communication AS cc ON c.id = cc.contact_id 
            WHERE school_id = '$schoolId' AND 
                cc.id IN (SELECT MAX(id) FROM contact_communication WHERE contact_id = c.id)
                ORDER BY cc.date DESC

问题是,这个查询只给我最新的通讯(这是我想要的),但不会列出没有通讯的联系人。

我已经在这3天了。有什么提示吗?

谢谢!

(PS:如果需要,我会编辑并提供更多信息。)

修改 答案(谢谢,ysrb)正在改变我的where子句:

SELECT c.id,
            c.f_name,
            c.l_name,
            c.address1,
            c.address2,
            c.city,
            c.state,
            c.zip,
            c.tel,
            c.school_id,
            c.email,
                ct.tel,
                cc.date,
                cc.reason,
                cc.result,
                cc.caller
                FROM contacts AS c
                LEFT OUTER JOIN contact_phones AS ct ON c.id = ct.contact_id
                LEFT OUTER JOIN contact_communication AS cc ON c.id = cc.contact_id 
            WHERE school_id = '$schoolId' AND 
                (cc.id IN (SELECT MAX(id) FROM contact_communication WHERE contact_id = c.id) OR cc.id IS NULL) 
                ORDER BY cc.date DESC

1 个答案:

答案 0 :(得分:2)

尝试:

SELECT c.id,
            c.f_name,
            c.l_name,
            c.address1,
            c.address2,
            c.city,
            c.state,
            c.zip,
            c.tel,
            c.school_id,
            c.email,
                ct.tel,
                cc.date,
                cc.reason,
                cc.result,
                cc.caller
                FROM contacts AS c
                LEFT OUTER JOIN contact_phones AS ct ON c.id = ct.contact_id
                LEFT OUTER JOIN contact_communication AS cc ON c.id = cc.contact_id 
            WHERE school_id = '$schoolId' AND 
                (cc.id = (SELECT MAX(id) FROM contact_communication WHERE contact_id = c.id) OR cc.ID IS NULL)
            ORDER BY cc.date DESC