I have 4 tables as follows:
----------- | ----------- | ------------- | ------------
caja | facturas | proveedores | productos
----------- | ----------- | ------------- | ------------
id | factura_id | proveedor_id | producto_id
fecha | proveedor_id | nombre | descripcion
monto | producto_id | direccion | precio
factura_id | monto | | unidad
descripcion | impuestos | |
What I want to get is: all cash movements; and those where invoice_id is not null, then it also shows me the name of the supplier and the description of the product.
What I try is the following:
SELECT caja.id, caja.fecha, caja.monto, caja.descripcion,
proveedores.nombre, productos.descripcion
FROM caja, facturas, proveedores, productos
WHERE caja.factura_id = facturas.factura_id AND facturas.proveedor_id =
proveedores.proveedor_id AND factura.producto_id =
productos.producto_id
The query works except for the detail that it only returns the cash movements where there is an invoice_id, and I have movements where there are no invoices, and I would like them to appear in the query as well.
Try this way, to leave it as a
JOIN EXPLÍCITO
:JOINS
one for each related tableIS NOT NULL
to filter the results of those whose invoice id is different from nullIn case you want to keep your query, it should be enough to add a condition
WHERE
like this to filter:The core part of your question is "all cash movements" so you could do something like this:
Detail:
caja
as the base table, and then we useLEFT JOIN
with the rest of the tables, which ensures us all the rows ofcaja
and those that match from the rest of the tables.JOINS
explicits, take it as a good practice, in addition to indicating an alias to each table that will make your life easiercaja
that do not havefactura_id
will produceNULL
in the columnsp.nombre
andpr.descripcion
.