I have the following two example tables
Orders Table
| order_id | linked_order1 | linked_order2 |
|---|---|---|
| 1001 | L005 | null |
| 1002 | null | null |
| 1003 | L006 | L007 |
Invoices Table
| order_id | linked_order_id | charge |
|---|---|---|
| 1001 | null | 4.27 |
| 1002 | null | 9.82 |
| 1003 | null | 7.42 |
| null | L005 | 2.12 |
| null | L006 | 1.76 |
| null | L007 | 3.20 |
I need to join these so the charges of all the orders (linked and otherwise) can be shown as part of the single order row. My desired output is something like this.
Desired Output
| order_id | linked_order1 | linked_order2 | invoices.charge | invoices.order_id | invoices.linked_order_id |
|---|---|---|---|---|---|
| 1001 | L005 | null | 4.27 | 1001 | null |
| 2.12 | null | L005 | |||
| 1002 | null | null | 9.82 | null | null |
| 1003 | L006 | L007 | 7.42 | null | null |
| 1.76 | null | L006 | |||
| 3.20 | null | L007 |
I can manage to get the main order into the table as follows.
SELECT
orders,
ARRAY(
SELECT AS STRUCT * FROM `invoices_table` WHERE order=orders.order_id) AS invoice
FROM
`orders_table` AS orders
I can run a separate query to union all of the invoice results into a single table for given order ids but I can't combine this with the above query with out getting errors.
Something like this...
SELECT
orders,
ARRAY(
SELECT AS STRUCT * FROM
(SELECT * FROM `invoices_table` WHERE order=orders.order_id
UNION ALL SELECT * FROM `invoices_table` WHERE linked_order_id=orders.linked_order1
UNION ALL SELECT * FROM `invoices_table` WHERE linked_order_id=orders.linked_order2)
) AS invoice
FROM
`orders_table` AS orders
But this gives me the correlated subqueries error.
[Update]
This is much simpler than I thought. The following query gives me what I was after.
SELECT
orders,
ARRAY(
SELECT AS STRUCT * FROM `invoices_table` WHERE order=orders.order_id OR linked_order_id IN(orders.linked_order1, orders.linked_order2)) AS invoice
FROM
`orders_table` AS orders
