SELECT O.ID, MAX(OP.VALUE) AS PREPAYMENT, SUM(EF.VALUE) AS PAYMENT
FROM b_sale_order O
LEFT JOIN `d_sale_order_prepayment` OP ON ( OP.order_id = O.ID )
LEFT JOIN `d_sale_order_excess_fare` EF ON ( EF.order_id = O.ID )
GROUP BY O.ID
$db->query('INSERT INTO `users` VALUES (?n, "?s", "?i", "?s")', null, 'Иван', '25', 'г. Клин, ЗАО "Рога и копыта"');
$db->query('INSERT INTO `users` VALUES (?n, ?s)', 1, 'Иван');
select
sum(case when date>now() - interval 7 day THEN index END) as sum1,
sum(case when date>now() - interval 14 day and date<now() - interval 7 day THEN index END) as sum2
from table
WHERE
date>now() - interval 14 day
SELECT
users.name
FROM users
INNER JOIN user_roles
ON user_roles.user_fk = users.user_id
INNER JOIN role_permissions
ON user_roles.role_fk = role_permissions.permission_fk
INNER JOIN permissions
ON user_roles.role_permission_id = permissions.id
WHERE
users.name='Ivan' AND permissions.name= 'auth-site'