使用分组依据后,在左连接中丢失记录

时间:2010-01-16 04:47:48

标签: mysql

执行此查询后基本上是:

SELECT
`view_customer_locations`.customerid,
`view_customer_locations`.community_groupid,
`view_customer_locations`.community_group,


`view_sip_user_agents`.sip_user_agentid,
`view_sip_user_agents`.didid,
`view_sip_user_agents`.temporary_didid,
`view_sip_user_agents`.active_did,
GROUP_CONCAT( (IF(`view_sip_user_agents`.active_did = 'permanent', cast(`permanent_dids`.did  as char(10)), cast(`temporary_dids`.did as char(10)))) SEPARATOR ', ') as did,

`view_sip_user_agents`.sip_user_agents_date_archived

FROM `view_customer_locations`
LEFT JOIN `view_sip_user_agents` on `view_customer_locations`.customerid = `view_sip_user_agents`.customerid
LEFT JOIN `dids` AS permanent_dids ON `view_sip_user_agents`.didid = `permanent_dids`.id
LEFT JOIN `dids` AS temporary_dids ON `view_sip_user_agents`.temporary_didid = `temporary_dids`.id
Group by `view_customer_locations`.customerid

我仍然想要view_customer_locations表中的所有行..但是我丢失了view_customer_locations表中view_sip_user_agents表中没有相应记录的任何条目。我还希望条目按customerid分组..这样每个客户在结果查询中只有一个条目。

如果我删除group by子句,我会从view_customer_locations表中获取所有内容,但自然我每个客户有多个条目,这不是我想要的。

请帮助

2 个答案:

答案 0 :(得分:2)

虽然MySQL确实让你“逃脱”表达GROUP BY子句,其SELECT中的字段可能会在GROUP BY字段中变化(理论上选择“任意/随机值“),正如你所注意到的那样,这种构思错误,逻辑上没有充分根据的操作的结果有时令人惊讶。

尝试使用正确的SQL,例如在“分组依据”的字段上使用MAX运算符。如果这些字段严格按分组字段确定的隐含假设是正确的,这不可能以任何方式损害您的结果,对吧?然而,有时您会发现结果确实出现或改变(意味着隐含的假设是简单的错误)。

在您的情况下,由于某些字段中的某些字段可能统一为NULL,并且MAX在这种情况下未必明确定义,您可能会进一步尝试使用{{1}当然,那里。

答案 1 :(得分:0)

我认为GROUP BY不是你真正想要的。 DISTINCT更正确,因为它会消除重复,但结果是在非分组字段中定义的

SELECT DISTINCT
`view_customer_locations`.customerid,
`view_customer_locations`.community_groupid,
`view_customer_locations`.community_group,


`view_sip_user_agents`.sip_user_agentid,
`view_sip_user_agents`.didid,
`view_sip_user_agents`.temporary_didid,
`view_sip_user_agents`.active_did,
GROUP_CONCAT( (IF(`view_sip_user_agents`.active_did = 'permanent', cast(`permanent_dids`.did  as char(10)), cast(`temporary_dids`.did as char(10)))) SEPARATOR ', ') as did,

`view_sip_user_agents`.sip_user_agents_date_archived

FROM `view_customer_locations`
LEFT JOIN `view_sip_user_agents` on `view_customer_locations`.customerid = `view_sip_user_agents`.customerid
LEFT JOIN `dids` AS permanent_dids ON `view_sip_user_agents`.didid = `permanent_dids`.id
LEFT JOIN `dids` AS temporary_dids ON `view_sip_user_agents`.temporary_didid = `temporary_dids`.id
Group by `view_customer_locations`.customerid