I need some help figuring out the SQL for combining two tables into one table. I’m wanting to combine the tables and display the data on different rows for each table, but what I have below makes only one row.
Here are the tables:
CREATE TABLE tenant_invoices(
invoice_id INT,
col1 INT,
col2 INT
)
CREATE TABLE tenant_payments(
pmt_invoice_id INT,
colA INT,
colB INT
)
Here are the temporary tables I need to create:
CREATE TEMPORARY TABLE tenant_invoices
SELECT * FROM invoices
CREATE TEMPORARY TABLE tenant_payments
SELECT * FROM payments
select ti.*, tp.*
from tenant_invoices ti
left join tenant_payments tp
on ti.invoice_id = tp.pmt_invoice_id
ORDER BY ti.invoice_date DESC;
This results in two tables merge together but only one row is created:
invoice_id col1 col2 pmt_invoice_id colA ColB
1 ABC XYZ 1 111 222
I’m wanting the table to be able to merge the tables together so I get all the columns, but instead of one row with combined data I want the rows separated so I can loop through the data in a more logical fashion:
invoice_id col1 col2 pmt_invoice_id colA ColB
1 ABC XYZ null null null
1 111 222
Is there a way I can accomplish this with SQL?
Thanks.
To achieve this result…
invoice_id col1 col2 pmt_invoice_id colA ColB 1 ABC XYZ null null null 1 111 222You can use
UNION ALLlike so:As already mentioned, to simply stack the two tables on top of each other, then you align the columns and use
UNION ALL. If you wish to remove duplicates, you can useUNION.