-- Denormalized onto the invoice (rather than only joined through
-- customer_id) so invoice listing/reporting queries can filter by
-- company directly without a join — this is exactly the kind of
-- high-read table where that duplication is worth it.
ALTER TABLE monthly_invoices
    ADD COLUMN company_id BIGINT UNSIGNED NULL AFTER customer_id;

UPDATE monthly_invoices mi
JOIN customers c ON c.id = mi.customer_id
SET mi.company_id = c.company_id
WHERE mi.company_id IS NULL;

ALTER TABLE monthly_invoices
    MODIFY COLUMN company_id BIGINT UNSIGNED NOT NULL,
    ADD KEY idx_invoices_company (company_id),
    ADD CONSTRAINT fk_invoices_company
        FOREIGN KEY (company_id) REFERENCES companies (id)
        ON DELETE RESTRICT ON UPDATE CASCADE;
