Mysql Loop By Query Result - mysql

I have this query that produces a list of foreign keys:
SELECT ad_id
FROM ads AS i
INNER JOIN ads_earnings AS e
ON i.ad_id = e.earning_ad_id
GROUP BY i.ad_id
I want to use that as the parameter for this query in a loop:
INSERT INTO ads_stats_traffic
(traffic_ad_id,traffic_country_id,traffic_paid,traffic_verified,traffic_total)
(
SELECT earning_ad_id, earning_country_id, earning_paid, SUM(earning_verified), COUNT(earning_id)
FROM ads_earnings
WHERE earning_ad_id = ?
GROUP BY earning_paid, earning_country_id
)
How do I do that?

Using a nested subquery with in should work:
INSERT INTO ads_stats_traffic
(traffic_ad_id,traffic_country_id,traffic_paid,traffic_verified,traffic_total)
(
SELECT earning_ad_id, earning_country_id, earning_paid, SUM(earning_verified), COUNT(earning_id)
FROM ads_earnings
WHERE earning_ad_id in
(
SELECT ad_id
FROM ads AS i
INNER JOIN ads_earnings AS e
ON i.ad_id = e.earning_ad_id
GROUP BY i.ad_id
)
GROUP BY earning_paid, earning_country_id
)

Related

Subquery and Filter Eloquent Laravel using Yajra Datatables

I want to view bonus recapitulation from transaction and i try write code in phpmyadmin like
SELECT
tbl2.name, b.nama_bonus,
SUM(
CASE
WHEN b.nama_bonus REGEXP 'saldo' THEN tbl2.jumlah_transaksi * b.nominal_bonus
WHEN b.nama_bonus REGEXP 'bintang' AND tbl2.nama_kategori REGEXP 'transfer' THEN FLOOR(tbl2.total_nominal_transaksi / b.keterangan_bonus)
ELSE FLOOR(tbl2.total_nominal_transaksi / b.keterangan_bonus)
END
) AS bonus_member
FROM
(
SELECT tbl1.*, u.name, pc.nama_kategori, COUNT(tbl1.nominal_transaksi) AS jumlah_transaksi, SUM(tbl1.nominal_transaksi) AS total_nominal_transaksi FROM
(
SELECT no_invoice, product_category_id, nominal_transaksi, user_id, status_transaksi_id FROM transactions
WHERE status_transaksi_id = 1
) AS tbl1
JOIN users u ON u.id = tbl1.user_id
JOIN product_categories pc ON pc.id = tbl1.product_category_id
GROUP BY u.id, pc.id
) AS tbl2
JOIN bonus b ON b.product_category_id = tbl2.product_category_id
GROUP BY b.nama_bonus, tbl2.name
ORDER BY tbl2.name
And the result is result query image
how to implement mysql code with eloquent using yajra datatables and also filter the data?

Mysql Select unique record based on multiple columns and display only group and sum amount

Hi I am trying to query a table that conatains multiple duplicates on Code,Amount and Status How will I do this if I only one to get a result group according to the client_group name and get the sum of amount under that group
SELECT `client`.`client_group`
, FORMAT(SUM(`Data_result`.`Data_result_amount` ),2) as sum
FROM
`qwer`.`Data_result`
INNER JOIN `qwer`.`Data`
ON (`Data_result`.`Data_result_lead` = `Data`.`Data_id`)
INNER JOIN `qwer`.`Data_status`
ON (`Data_result`.`Data_result_status_id` = `Data_status`.`Data_status_id`)
INNER JOIN `qwer`.`client`
ON (`Data`.`Data_client_id` = `client`.`client_id`)
WHERE `Data_status`.`Data_status_name` IN ('PAID') AND MONTH(`Data_result`.`result_ts`) = MONTH(CURRENT_DATE())
AND YEAR(`Data_result`.`result_ts`) = YEAR(CURRENT_DATE())
GROUP BY `client`.`client_group`
Result of said query:
Table
Try to distinct before run the 'sum' check whether this solve your problem
SELECT `client_group` , FORMAT(SUM(`Data_result_amount` ),2) as sum from (
SELECT DISTINCT `client`.`client_group` , `Data_result`.`Data_result_amount`
FROM
`qwer`.`Data_result`
INNER JOIN `qwer`.`Data`
ON (`Data_result`.`Data_result_lead` = `Data`.`Data_id`)
INNER JOIN `qwer`.`Data_status`
ON (`Data_result`.`Data_result_status_id` = `Data_status`.`Data_status_id`)
INNER JOIN `qwer`.`client`
ON (`Data`.`Data_client_id` = `client`.`client_id`)
WHERE `Data_status`.`Data_status_name` IN ('PAID') AND MONTH(`Data_result`.`result_ts`) = MONTH(CURRENT_DATE())
AND YEAR(`Data_result`.`result_ts`) = YEAR(CURRENT_DATE())
) T
GROUP BY `client_group`
you can check the query here http://sqlfiddle.com/#!9/36a3f8/6

Add complex mysql query to seach model in Yii2

I want to use the default search and pagination in yii2. But the query is complex and I don't know how can I add it to the search model! This is the query:
SELECT p.*,po_sum,rpo_sum,so_sum
FROMproduct p
LEFT JOIN (
SELECT id,product_id , IF(sum(quantity) IS NULL, 0, sum(quantity)) AS po_sum
FROM purchase_order_products inner join purchase_order on purchase_order.id = purchase_order_products.purchase_order_id
Where purchase_order.status = 'Approved'
GROUP BY product_id )
subcount ON p.id = subcount.product_id
LEFT JOIN (
SELECT id,product_id , sum(quantity) AS rpo_sum
FROM return_purchase_order_products inner join return_purchase_order on return_purchase_order.id = return_purchase_order_products.purchase_order_id Where return_purchase_order.status = 'Approved'
GROUP BY product_id )
subcount2 ON p.id = subcount2.product_id
LEFT JOIN (
SELECT product_id , sum(quantity_ordered) AS so_sum
FROM sales_order_item inner join sales_order on sales_order.id = sales_order_item.sales_order_id Where sales_order.order_status = 'complete'
GROUP BY product_id )
subcount3 ON p.id = subcount3.product_id
order by po_sum DESC,rpo_sum DESC
Any help?
If you use MySql >= 5.7.7 the easiest way is to create a view with that query and use it in the tableName method.
You need that version of MySql because you cant use subquery in from clause during view creation in previous versions.

Count invitation response against events and response codes

I have this table for Response Codes:
And this table for invitations:
My query so far gives this:
While I want to achieve this:
MY QUERY:
SELECT
i.eventId
,code.responseCode
,COUNT(i.attendeeResponse) responseCount
FROM invitations i
LEFT JOIN response_codes code
ON code.responseCode = i.attendeeResponse
GROUP BY i.eventId, code.responseCode, i.attendeeResponse;
SQLFiddle
You need to construct a cartesian product of all eventIds and responseCodes at first (you can achieve it with join without condition):
select c.eventId
, c.responseCode
, count( i.attendeeResponse ) as responseCount
from ( select distinct t1.responseCode
, t2.eventId
from `response_codes` t1
join `invitations` t2 ) c
left join `invitations` i on c.responseCode = i.attendeeResponse and c.eventId = i.eventId
group by c.eventId, c.responseCode;
SQLFiddle
You need to cross join the responsecode table to get the all combinations of eventid and responsecode.
SQL Fiddle
SELECT distinct
i.eventId
,code.responseCode
,case when t.responseCount is null then 0
else t.responsecount end rcount
FROM invitations i
cross JOIN response_codes code
left join
(SELECT i.eventId
,code.responseCode
,COUNT(i.attendeeResponse) responseCount
FROM invitations i
JOIN response_codes code
ON code.responseCode = i.attendeeResponse
group by i.eventid, code.responsecode) t
on t.responsecode =code.responsecode and t.eventid = i.eventid
order by i.eventid, code.responsecode desc
Another lazy way could be:
SELECT B.EVENTID,A.RESPONSECODE,
IFNULL((SELECT COUNT(*) FROM INVITATIONS C WHERE C.EVENTID = B.EVENTID AND C.ATTENDEERESPONSE = A.RESPONSECODE),0) AS 'responseCount'
FROM
RESPONSE_CODES A,
INVITATIONS B
GROUP BY A.RESPONSECODE,B.EVENTID
ORDER BY EVENTID ASC,RESPONSECODE DESC
SQL Fiddle

Replacing sub query with join in mysql

I have a mysql query like...
SELECT OrderTransaction.buyer, OrderTransaction.parent_id
FROM order_transactions as OrderTransaction
INNER JOIN (
SELECT buyer
FROM order_transactions as dy
left join orders as ebay on ebay.id=dy.parent_id
where ebay.status='0' and dy.parent_id IN (
SELECT parent_id
FROM order_shipping_details as ds
left join orders as ebays on ebays.id=ds.parent_id
where ebays.status='0' and ebays.combined=0
GROUP BY ds.Street
HAVING count(ds.id) > 1
) and ebay.combined=0
group by dy.buyer
) dup ON dup.buyer=OrderTransaction.buyer
left join orders as ebay on ebay.id=OrderTransaction.parent_id
where ebay.market_type!='shopclue' and ebay.status='0' and ebay.combined=0
I need to optimize this query and want to remove the inner select with joins.
Any help would be appreciated. Thanks in advance.
Try this code below might be running faster than the one u currently using:
DROP TEMPORARY TABLE IF EXISTS temp1;
CREATE TEMPORARY TABLE temp1;
SELECT buyer
FROM order_transactions AS dy
LEFT JOIN orders AS ebay ON ebay.id=dy.parent_id
WHERE ebay.status='0'
AND dy.parent_id
IN (
SELECT parent_id
FROM order_shipping_details AS ds
left join orders AS ebays ON ebays.id=ds.parent_id
where ebays.status='0' and ebays.combined=0
GROUP BY ds.Street
HAVING count(ds.id) > 1)
AND ebay.combined= '0'
;
SELECT
OrderTransaction.buyer,
OrderTransaction.parent_id
FROM order_transactions AS OrderTransaction
INNER JOIN temp1 AS tmp ON tmp.buyer = OrderTransaction.buyer
LEFT JOIN orders AS ebay ON ebay.id = OrderTransaction.parent_id
WHERE ebay.market_type! = 'shopclub' AND ebay.status = '0' and ebay.combined = '0'
Please let me know if you have any questions!