SELECT `p`.`title`, `p`.`supplement`, `p`.`link`, `p`.`file`,
`u`.`avatar`, `p`.`pid`, `u`.`lastname`, `u`.`uid`, `c`.`comments`,
CONCAT(IFNULL(`u`.`firstname`, ''), ' ', IFNULL(`u`.`surname`, '')) AS `name`
FROM (
SELECT `c`.`pid`,
JSON_ARRAYAGG(JSON_OBJECT(
'name', CONCAT(IFNULL(`u`.`firstname`, ''), " ", IFNULL(`u`.`surname`, '')),
'avatar', `u`.`avatar`,
'lastname', `u`.`lastname`,
'value', `c`.`value`,
'cid', `c`.`cid`,
'answers', `a`.`answers`
)) AS `comments`
FROM (
SELECT `a`.`cid`,
JSON_ARRAYARG(JSON_OBJECT(
'name', CONCAT(IFNULL(`u`.`firstname`, ''), " ", IFNULL(`u`.`surname`, '')),
'avatar', `u`.`avatar`,
'lastname', `u`.`lastname`,
'value', `a`.`value`,
'cid', `a`.`cid`,
'answer', `a`.`answer`
)) AS `answers`
FROM `comments` AS `c`
JOIN `comments` AS `a` ON `a`.`cid` = `c`.`cid`
LEFT JOIN `users` AS `u` ON `u`.`uid` = `a`.`uid`
WHERE `c`.`pid` = :postId
GROUP BY `a`.`cid`
) AS `a`
RIGHT JOIN `comments` AS `c` ON `c`.`cid` = `a`.`cid`
LEFT JOIN `users` AS `u` ON `c`.`uid` = `u`.`uid`
WHERE `c`.`pid` = :postId
GROUP BY `c`.`pid`
) AS `c`
RIGHT JOIN `posts` AS `p` ON `p`.`pid` = `c`.`pid`
LEFT JOIN `users` AS `u` ON `u`.`uid` = `p`.`uid`
WHERE `p`.`pid` = :postId
SELECT AVG(`age`)
FROM `CUSTOMER`
WHERE `CUSTOMER_KEY` IN (
SELECT `CUSTOMER_KEY`
FROM `PURCHACE`
WHERE `PRODUCT_KEY` IN (
SELECT `PRODUCT_KEY`
FROM `PRODUCT`
WHERE `NAME` = 'плюшевый мишка'
) AND `DATE` BETWEEN '2018-01-01' AND '2018-12-31'
)
SELECT AVG(`age`)
FROM (
SELECT DISTINCT `c`.`CUSTOMER_KEY`, `c`.`AGE` AS `age`
FROM `PRODUCT` AS `p`
JOIN `PURCHACE` AS `pu`
ON `p`.`NAME` = 'плюшевый мишка'
AND `pu`.`DATE` BETWEEN '2018-01-01' AND '2018-12-31'
AND `pu`.`PRODUCT_KEY` = `p`.`PRODUCT_KEY`
JOIN `CUSTOMER` AS `c`
ON `c`.`CUSTOMER_KEY` = `pu`.`CUSTOMER_KEY`
) AS `t`
SELECT `recipe_id`, `ingredient_id`
FROM `recipe_ingredients`
WHERE `ingredient_id` IN (501, 900)
SELECT `recipe_id`, COUNT(*) AS `count`,
SUM(`ingredient_id` IN (501, 900)) AS `avail`
FROM `recipe_ingredients`
GROUP BY `recipe_id`
HAVING `count` = `avail`
SELECT `o`.`num`, `o`.`createdon`, `o`.`cost`, `o`.`status`, `p`.`products`
FROM `modx_ms2_orders` AS `o`
LEFT JOIN (
SELECT `order_id`,
JSON_ARRAYAGG(
JSON_OBJECT('name', `name`, 'price', `price`, 'count', `count`)
) AS `products`
FROM `modx_ms2_order_products`
GROUP BY `order_id`
) AS `p` ON `p`.`order_id` = `o`.`id`
WHERE `o`.`user_id` = 106
SELECT `day`, `priority`, `count`
FROM (
(SELECT 'today' AS `day`, `priority`, COUNT(*) AS `count`
FROM `table`
WHERE `time` >= CURDATE() AND `time` < CURDATE() + INTERVAL 1 DAY
GROUP BY `priority`)
UNION ALL (SELECT 'yesterday', `priority`, COUNT(*)
FROM `table`
WHERE `time` >= CURDATE() + INTERVAL 1 DAY AND `time` < CURDATE() + INTERVAL 2 DAY
GROUP BY `priority`)
) AS `t`