0
如果我有表日誌:基於結果從另一個查詢的MySQL更新表
ID Date P_id TYPE
-------------------------------
1 2016-9-1 11 adClick
2 2016-9-1 22 adComplete
3 2016-9-1 11 adClick
4 2016-9-3 22 adClick
5 2016-9-3 22 adClick
6 2016-9-1 11 adClick
7 2016-9-3 22 adComplete
8 2016-9-1 11 adClick
9 2016-9-3 11 adClick
-------------------------------
,並具有相同日期&的p_id另一個表報告如下:
ID Date P_id clicks
--------------------------------
1 2016-9-1 11
2 2016-9-3 11
3 2016-9-1 11
4 2016-9-3 11
5 2016-9-1 22
6 2016-9-1 11
5 2016-9-1 22
---------------------------------
我需要MySQL查詢根據密鑰(日期& P_id)在報表中點擊點擊數,如果有餘數,則隨機添加一個直到完成剩餘部分,並選擇相同的鍵:
clicks =
count of rows having (Date & P_id) in logs table
------------------- Divistion (/) -------------------
count of rows having (Date & P_id) in Report and Type is adClick
通過鍵(日期& P_ID)和事件類型各組的計數adClick在日誌表是:
2016-9-1 11 --- count--> 4
2016-9-1 22 --- count--> 0
2016-9-3 11 --- count--> 1
2016-9-3 22 --- count--> 2
而在報告表數:
2016-9-1 11 --- count--> 3
2016-9-1 22 --- count--> 2
2016-9-3 11 --- count--> 2
2016-9-3 22 --- count--> 0
所以表會成爲:
ID Date P_id clicks
--------------------------------
1 2016-9-1 11 4/3 = 1 and 1 as remainder
2 2016-9-3 11 1/2 = 0 and 1 as remainder
3 2016-9-1 11 4/3 = 1 and 1 as remainder
4 2016-9-3 11 1/2 = 0 and 1 as remainder
5 2016-9-1 22 0/2 = 0
6 2016-9-1 11 4/3 = 1 and 1 as remainder
5 2016-9-1 22 0/2 = 0
---------------------------------
樣本解釋更多第一行:
2016-9-1 11 4/3
4 rows (2016-9-1 11) in logs table with type=adClick by
3 row (2016-9-1 11) in report table
我已經做了保存,而不其餘的點擊的一部分,所以在報告表我的查詢記錄:
ID Date P_id clicks
--------------------------------
1 2016-9-1 11 1
2 2016-9-3 11 0
3 2016-9-1 11 1
4 2016-9-3 11 0
5 2016-9-1 22 0
6 2016-9-1 11 1
5 2016-9-1 22 0
---------------------------------
現在我想傳播餘 - 也許隨機 - 到報告表,以便同一個鍵的總和保持不變:
ID Date P_id clicks
--------------------------------
1 2016-9-1 11 1 + 1
2 2016-9-3 11 0 + 1
3 2016-9-1 11 1
4 2016-9-3 11 0
5 2016-9-1 22 0
6 2016-9-1 11 1
5 2016-9-1 22 0
---------------------------------
所以點擊了(2016年9月1日11)的總和,現在是4兩個表。
這裏是我用用剩餘部分之前更新查詢:
UPDATE report AS r
INNER JOIN
(
SELECT DATE(ctr_date) as report_date, report.placement_id, count(*) as cnt_report, cnt_event_type
FROM report
INNER JOIN
(
SELECT DATE(ctr_date) as event_date, placement_id, SUM(event_type = 'adClick') as cnt_event_type
FROM logs
GROUP BY DATE(ctr_date),placement_id
) inner_report
ON report.date = inner_report.event_date AND report.placement_id = inner_report.placement_id
GROUP BY report.date, report.placement_id
) result_table
ON r.date = result_table.report_date AND r.placement_id= result_table.placement_id
SET r.clicks = COALESCE((cnt_event_type - MOD(cnt_event_type,cnt_report))/cnt_report ,0);
我想使用相同的查詢,但有限制(餘數)爲相同的密鑰和使用:
SET r.clicks = r.clicks + 1
在我看來,它可能更容易和更易於維護,要麼在代碼中執行此操作,要麼添加存儲的存儲過程來執行此操作。哪種方式最好取決於您的使用情況。 – user2120275