I need to insert values in a table by SQL query that selects the different id_cliente
that exist in the table Clientes
with its amount and the rest of the fields in the table Facturas
adding 1 to field num_factura
(is the invoice number of the client itself).
The idea is to do this every month to generate the monthly invoices of the clients and I want them to be stored in the Invoices table.
These are the tables and their respective fields:
Invoices
- bill_id (Key)
- customer_id
- num_factura
- date_fact
- amount
Customers
- client_id (key)
- total_price
The id_factura
field is a unique and self-reinforcing field.
The id_cliente
field can be repeated for each different num_factura
.
The date_data field is provided by me every month.
I've tried this and it duplicates all the values in the Facturas
table:
INSERT INTO Facturas ( id_cliente, num_factura, fecha_factura, importe )
SELECT Clientes.Id_cliente, Facturas.num_factura + 1, Facturas.fecha_factura,
Clientes.precio_total
FROM Clientes
INNER JOIN Facturas ON Clientes.Id_cliente = Facturas.id_cliente
WHERE Clientes.Id_cliente IN (SELECT DISTINCT Id_cliente FROM Clientes);
When I perform the query for the first time it executes correctly but the next time the execution repeats everything that existed in the table Invoices and also the new also, going from 100 records, to 200, 400, 800, etcetera.
How can this situation be solved?
Example of what happens when executing:
Original Table Invoices:
id_factura id_cliente num_factura fecha_factura importe
1 10 001 31/08/2016 105€
2 11 001 31/08/2016 95€
Table Invoices after the first INSERT execution
id_factura id_cliente num_factura fecha_factura importe
1 10 001 31/08/2016 105€
2 11 001 31/08/2016 95€
3 10 002 31/08/2016 105€
4 11 002 31/08/2016 95€
Table Invoices after second INSERT execution
id_factura id_cliente num_factura fecha_factura importe
1 10 001 31/08/2016 105€
2 11 001 31/08/2016 95€
3 10 002 31/08/2016 105€
4 11 002 31/08/2016 95€
5 10 002 31/08/2016 105€
6 11 002 31/08/2016 95€
7 10 003 31/08/2016 105€
8 11 003 31/08/2016 95€
What I want to get after the second consultation ...:
id_factura id_cliente num_factura fecha_factura importe
1 10 001 31/08/2016 105€
2 11 001 31/08/2016 95€
3 10 002 31/08/2016 105€
4 11 002 31/08/2016 95€
5 10 003 31/08/2016 105€
6 11 003 31/08/2016 95€