SELECT contragent ,
COUNT(*) OVER() as `total_count` FROM (
SELECT `contragents`.`id`,
CONCAT_WS('', '{\"id\":\"', A.`id`,'\"', ',\"ap_name\":\"', A.`ap_name`,'\"', ',\"ap_city_id\":\"', AA.`name_ru`,'\"', ',\"itn\":\"', A.`itn`,'\"', ',\"kpp\":\"', A.`kpp`,'\"', ',\"okpo\":\"', A.`okpo`,'\"','}') AS `entpr_id`,
CONCAT_WS('', '{\"id\":\"', B.`id`,'\"', ',\"ap_name\":\"', B.`ap_name`,'\"', ',\"ap_city_id\":\"', AB.`name_ru`,'\"', ',\"itn\":\"', B.`itn`,'\"', ',\"kpp\":\"', B.`kpp`,'\"', ',\"okpo\":\"', B.`okpo`,'\"','}') AS `contragent`,
`contragents`.`type`, `contragents`.`ctype`, `contragents`.`resp`, `contragents`.`author`,
`contragents`.`code`, `contragents`.`contract`, `contragents`.`owner`,
COUNT(*) OVER() as `total_count`
FROM `contragents`
LEFT JOIN `companies` A on A.`id` = `contragents`.`entpr_id`
LEFT JOIN `companies` B on B.`id` = `contragents`.`contragent`
LEFT JOIN `cities` AA on AA.`id` = `A`.`ap_city_id`
LEFT JOIN `cities` AB on AB.`id` = `B`.`ap_city_id`
WHERE
`contragents`.`id` IS NOT NULL AND ( `contragents`.`entpr_id` IN (1000004688) )
) AS res
WHERE contragent
LIKE '%Ап%' ORDER BY substring_index(contragent,'\"ap_name\":',-1) LIMIT 50 OFFSET 0;