Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- SELECT
- cp.ref
- , cp.id
- , cp.description
- , cp.phones AS phone
- , cp.spd_id
- , IFNULL(t.`sum`, 0) AS total_cost
- FROM order_ttn_contact_persons AS cp
- LEFT JOIN
- (
- SELECT
- ot.contact_person_id
- , IFNULL(SUM(ot.cost), 0) AS `sum`
- FROM order_contact_person AS ot
- LEFT JOIN order_ttn_contact_persons AS cp ON cp.id = ot.contact_person_id
- WHERE
- ot.insert_date = CURRENT_DATE
- GROUP BY ot.contact_person_id
- ) AS t ON t.contact_person_id = cp.id
- LEFT JOIN spd_order_ttn_contact_person sotcp ON sotcp.order_ttn_contact_person_id = cp.id
- LEFT JOIN spd ON sotcp.spd_id = spd.id
- WHERE (
- (cp.active = 1
- AND (spd.invoice = 0 OR spd.invoice IS NULL)
- )
- OR :SPD_ID IS NOT NULL
- )
- AND (:SPD_ID IS NULL OR sotcp.spd_id = :SPD_ID)
- ORDER BY total_cost
- LIMIT 1;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement