求问:sql中多表关联查询求和,主表的数据根据副表的数据重复相加了,等于数据翻倍,这种请怎么处理
SELECTsum(d.go),sum(a.letter1),a.region_id1,d.region_idFROMdwdsASarightJOINpowerASdON...
SELECTsum(d.go),sum(a.letter1),a.region_id1,d.region_idFROM dwds AS a right JOIN power AS d ON d.platform_id = a.platform_id1 AND d.region_id = a.region_id1 AND d.time = a.time1WHERE `time` BETWEEN 1535040000 AND 1535126399 or `time1` BETWEEN 1535040000 AND 1535126399GROUP BY a.platform_id1,a.region_id1上面是我现在的查询语句,问题就处在当表a有多条数据的时候,就会依据表d的多条数据去重复相加,这样得出的结果就是表d数据条数的倍数,各位大佬,帮忙看下,应该怎么做修改,对了还有就是,这个是用在tinkphp框架里面的,如果大佬们能改成tinkphp的写法,就万分感谢了
展开
1个回答
展开全部
首先,我怀疑你or没用明白,该括号括起来的地方没括起来。
然后,你可以先把a表和d表分别汇总,然后再关联起来。
select sum(d.go),sum(a.letter1),a.region_id1,d.region_id
from
(select region_id1,platform_id1,time1,sum(a.letter1) letter1 from dwds where `time1` BETWEEN 1535040000 AND 1535126399 group by region_id1,platform_id1,time1) a
right join
(select region_id,platform_id,time,sum(go) go from power where time BETWEEN 1535040000 AND 1535126399 group by region_id,platform_id,time) d
ON d.platform_id = a.platform_id1 AND d.time = a.time1
group by a.region_id1,d.region_id
另外,你a.region_id1和d.region_id是相等的,你select里都查出来干嘛?
追问
a.region_id1和d.region_id这两个只是在测试的时候打印出来方面看数据的,你这个方法学到了,我先测试下,看着你写的语句应该不是很大的问题来着,谢谢了哈·
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询