SELECT *
FROM `table`
ORDER BY (`phone` = :phone) * 8 +
(`lastName` = :lastName) * 2 +
(`firstName` = :firstName) * 2 +
(`middleName` = :middleName) * 2 +
(`city` = :city)
DESC
SELECT `v`.`id_user`, `v`.`count`, ...
FROM (
SELECT `id_user`, COUNT(DISTINCT FROM_UNIXTIME(time_vizit, '%Y%m%d')) AS `count`
FROM `vizits`
WHERE `time_vizit` BETWEEN UNIX_TIMESTAMP(:startTime) AND UNIX_TIMESTAMP(:endTime)
AND `id_client` = :clientId
GROUP BY `id_user`
HAVING COUNT(*) > 2
) AS `v`
LEFT JOIN `users_hotspot` AS `uh` ON `uh`.`id_user` = `v`.`id_user`
SET @rand = (SELECT (MAX(`id`)-MIN(`id`))*RAND()+MIN(`id`) FROM `localities``);
SELECT * FROM `localities` WHERE WHERE `id` > @rand LIMIT 1;
SELECT DISTINCT `t`.`lead_id`
FROM `table` AS `t`
JOIN `table` AS `t1` ON `t1`.`lead_id` = `t`.`lead_id`
AND `t1`.`field_id` = 805312 AND `t1`.`field_value` = 1417294800
JOIN `table` AS `t2` ON `t2`.`lead_id` = `t`.`lead_id`
AND `t2`.`field_id` = 805316 AND `t2`.`field_value` = 2126254
SELECT `lead_id`
FROM `table`
WHERE (`field_id` = 805312 AND `field_value` = 1417294800)
OR (`field_id` = 805316 AND `field_value` = 2126254)
GROUP BY `lead_id`
HAVING COUNT(DISTINCT `field_id`) = 2
SELECT `d`.*, `i`.`file_name` AS `face_foto`, `dif`.`filial_count`,
IFNULL(`rw`.`reviews_count`, 0), IFNULL(`rw`.`doctor_rating`, 0)
FROM (
SELECT `df`.`doctor_id`, COUNT(*) AS `filial_count`
FROM `clinic_filials` AS `cf`
JOIN `doctor_in_filials` AS `df` ON `df`.`filial_id` = `cf`.`id`
WHERE `cf`.`city_id` = 1
GROUP BY `df`.`doctor_id`
) AS `dif`
JOIN `doctors` AS `d` ON `d`.`id` = `dif`.`doctor_id`
LEFT JOIN `images` AS `i` ON `i`.`doctor_id` = `d`.`id`
AND `i`.`type` = "doctor_face"
LEFT JOIN (
SELECT `doctor_id`, COUNT(*) AS `reviews_count`,
AVG(`rating_doctor`) AS `doctor_rating`
FROM `reviews`
GROUP BY `doctor_id`
) AS `rw` ON `rw`.`doctor_id` = `d`.`id`