Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello, Im a beginner in MySQL. Im trying to query out some data from a voip calling card database for which I needed to join multiple table. It was giving correct output till there was two left join table, but when I added third table then the "total duration" column is giving wrong output.

My First query looked like this and the output was in this screencap ( http://i.stack.imgur.com/M8JN6.png ):


SQL
select c.login,cname.Name,cname.LastName,DATE_FORMAT(Creation_Date,'%d-%m-%y')as regdate,DATE_FORMAT((Select max(call_start) from calls where calls.id_client = c.id_client),'%d-%m-%y') as lastcall, c.account_state,sum(cdr.duration / 60) as total_duration from clientsshared as c
    left join invoiceclients as cname on cname.IdClient = c.id_client
    left join calls as cdr on cdr.id_client = c.id_client
    where c.id_reseller='10' group by c.id_client order by total_duration desc limit 100



The new query is like this which gives wrong output, please check the screencap ( http://i.stack.imgur.com/usce8.png ):


SQL
select c.login,cname.Name,cname.LastName,DATE_FORMAT(Creation_Date,'%m-%d-%y')as regdate, 
	(Select max(data) from payments where payments.id_client = c.id_client) as lastpayment,
	(Select max(call_start) from calls where calls.id_client = c.id_client) as lastcall, 
	c.account_state,sum(cdr.duration / 60) as total_duration from clientsshared as c

	left join invoiceclients as cname on cname.IdClient = c.id_client
	left join payments as p on p.id_client = c.id_client
	left join calls as cdr on cdr.id_client = c.id_client
	where c.id_reseller='10' group by c.id_client order by total_duration desc limit 100
Posted
Updated 3-Aug-15 1:40am
v2

1 solution

You're multiplying the total duration for all calls for the client by the total number of payments the client has made.

The query doesn't actually use the left join to the payments table, so you can just remove it:
SQL
select 
    c.login,
    cname.Name,
    cname.LastName,
    DATE_FORMAT(Creation_Date,'%m-%d-%y')as regdate, 
    (Select max(data) from payments where payments.id_client = c.id_client) as lastpayment,
    (Select max(call_start) from calls where calls.id_client = c.id_client) as lastcall, 
    c.account_state,
    sum(cdr.duration / 60) as total_duration 
from 
    clientsshared as c
    left join invoiceclients as cname on cname.IdClient = c.id_client
    left join calls as cdr on cdr.id_client = c.id_client
where 
    c.id_reseller='10' 
group by 
    c.id_client 
order by 
    total_duration desc 
limit 100
 
Share this answer
 
Comments
Member 11881930 4-Aug-15 4:58am    
Thanks a lot, It Worked.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900