基本上,我有三个表:如何根据引用第三个表的条件排除数据,如何连接两个表?
- CDR,它包含字段
dst
(目的地),billsec
(持续时间),和calldate
- Intlrates,其中包含
code
(国家代码),和cost
(每分钟)。 - 和areacode,其中包含
areacode
,state
和city
。
目前我有添加了调用每个代码的总成本,以下声明:
SELECT
mapgtalkexten.Intlrates.`Code`,
sum(mapgtalkexten.Intlrates.Cost * (cdr.billsec/60)) as totals
FROM
cdr JOIN mapgtalkexten.Intlrates ON
((`Code` = SUBSTRING(dst, 4, 3) or `Code` = SUBSTR(dst, 4, 2))
and dst like "011%")
--The above limits the join to only calls where the destination phone number
--requires the exit code (011) and the country code is 2 or 3 digits
or (`Code` = SUBSTR(dst, 2, 3) and dst like "1%")
--The above was written to also join countries where the NANP format was used
--(i.e. +1787 for Puerto Rico.)
WHERE
cdr.calldate like "2012-11%"
and billsec >0
GROUP BY
mapgtalkexten.Intlrates.`Code`
输出的样本:
Code | totals
--------------
212 | 2.035
240 | 170.76
352 | 2.268
49 | 0.45
现在,我的问题是这样的:在NANP和非NANP代码之间,表没有区别。这意味着在我的加入中,两者都是:
011212
(摩洛哥)和1212
(纽约州)都增加到总数。第一个是好的,第二个在不应该的时候增加总数。
为了避免这种情况,有没有办法修改为连接成线沿线的东西第二个条件:
`Code` = SUBSTR(dst, 2, 3) AND SUBSTR(dst, 2, 3) != areacode.areacode
基本上使得它,这样它只会如果代码匹配和代码加入不在国家区号表中。
我认为有一种方法可以通过连接(或者可能存在)来实现,但是当涉及到数据库时我很不足,而且我完全不知道如何去实现它。对不起,如果有更多的信息你需要/这个问题是荒谬的。
顺便说一句。使用'LIKE'是一个计算负担(字符串比较+通配符)。你的cdr。像“2012-11%”一样可以重写为“YEAR(cdr.calldate)= 2012 AND MONTH(cdr.calldate)= 11'。还有一个优化的机会,因为你可以在你的表上为一年和一个月声明一些额外的索引,即使它们都来自同一列中的值。 –