CREATE TEMPORARY TABLE `tmp_table`
SELECT
rl.`parent_aff_id`,
(FLOOR(COUNT(*) / 2) * 1000) AS `amount`,
CONCAT('Бонус:', ' ', GROUP_CONCAT(rl.`aff_id` , ',')) AS
`description`,
'bonus' AS `source`,
COUNT(*) as `Ref_count`
FROM `uv_u_mlm_relations` rl
GROUP BY `parent_aff_id`
HAVING COUNT(*) MOD 2 = 0;
INSERT INTO `uv_u_ref`(`aff_id`, `amount`, `status`,`visit_id`,
`description`, `source`, `reference`, `reference_details`, `parent_ref_id`,
`child_ref_id`, `Ref_count`)
SELECT
t.`parent_aff_id`,
t.`amount`,
2 AS `status`,
0 AS `visit_id`,
t.`description`,
'bonus' AS `source`,
0 AS `reference`,
'Bonus' AS `reference_details`,
0 AS `parent_ref_id`,
0 AS `child_ref_id`,
t.`Ref_count`
FROM `tmp_table` t
LEFT JOIN `uv_u_referrals` rf ON t.`parent_aff_id` = rf.`aff_id` AND t.`source` = rf.`source`
WHERE rf.`aff_id` IS NULL;
UPDATE `uv_u_ref` rf
INNER JOIN `tmp_table` t ON t.`parent_aff_id` = rf.`aff_id`
AND t.`source` = rf.`source`
SET
rf.`amount` = t.`amount`,
rf.`description` = t.`description`,
rf.`Ref_count` = t.`Ref_count`
WHERE rf.`Ref_count` > 0 AND t.`Ref_count` > rf.`Ref_count`