mardi 10 février 2015

How to combine 3 queries into 1 including set?

I have 3 mysql queries and each does specific job, the problem is I can't figure out how to combine 3 queries into 1. I'll write down all 3 queries and explain what each does, thus you can figure out how to combine them into one.



SELECT DISTINCT ip FROM
units AS j
INNER JOIN
unit_info u ON j.id_unit_info = u.id
INNER JOIN
ap_info ap ON j.id_ap = ap.id_ap WHERE
j.checked_date BETWEEN '2015-01-01' AND '2015-01-31 23:59:59' ORDER BY INET_ATON(ip);


This query gets a list of unique ips from duplicates.



SET @start_date := '2015-02-07', @end_date := '2015-02-09', @ip := '172.19.106.121', @total_trx := 0, @total_rcv := 0, @curr_trx := 0, @curr_rcv := 0, @curr_con := 0, @lineitem := 0;


This sets user-defined variables to store iterations later on.



SELECT CONCAT(@start_date, CONCAT(' - ', @end_date)) AS DATE, connect_time, @ip as IP,
ROUND((TOTAL_TRANSMITTED+TOTAL_RECEIVED)/1048576) as TOTAL_MB FROM (
select j.checked_date, u.ip, u.mac, ap.transmitted, ap.received,
(@lineitem:=@lineitem+1) line,
(@prev_con:=@curr_con) ,
(@curr_con:=ap.connect_time),
(@prev_trx:=@curr_trx),
(@curr_trx:=ap.transmitted),
(@prev_rcv:=@curr_rcv),
(@curr_rcv:=ap.received),
(@transmittedVals:=IF(@prev_con>@curr_con,@curr_trx,ABS(@prev_trx-@curr_trx))) transmittedVals,
(@total_trx:=@total_trx+@transmittedVals) TOTAL_TRANSMITTED,
(@receivedVals:=IF(@prev_con>@curr_con,@curr_rcv,ABS(@prev_rcv-@curr_rcv))) receivedVals,
(@total_rcv:=@total_rcv+@receivedVals) TOTAL_RECEIVED
from units as j inner join unit_info u on j.id_unit_info=u.id
inner join ap_info ap on j.id_ap = ap.id_ap
where j.checked_date between @start_date and concat(@end_date,' 23:59:59') and u.ip = @ip) A WHERE @lineitem = line;


This iterates through the tables and calculates data usage for only one ip and date periods. Do I need to use some kind of loop technique or something else? Is there a way to perform query 3 for each ip from the list (query 1) using unique user-defined variables for them and select each ip with total_mb?


Aucun commentaire:

Enregistrer un commentaire