Good evening I hope you can guide me, I have two tables with the following information:
(Client Table)
clienteid nombre direccion telefono email
--------- ------- --------- -------- --------
001 gallo
002 salcedo
003 paul
41422102 sistema
(Movement Table)
movimientoid fecha cuentaid clienteid monto tipo descripcion
------------ ---------- -------- --------- -------- ------ -------------------
1 2018-11-01 CAJA-001 41422102 10000.00 1 Saldo Inicial
2 2018-11-01 CAJA-001 003 5000.00 -1 Compra Al Contado
3 2018-11-01 CAJA-001 003 100.00 -1 Compra Al Contado
4 2018-11-01 CAJA-001 41422102 100.00 -1 Compra Al Contado
I make a query with the two tables and I have ordered data:
SET @dispo=0;
SELECT movimientoId, DATE_FORMAT(fecha, '%d/%m/%y') fecha, descripcion, cliente.clienteid
IF(tipo=1, monto, NULL) deposito, IF(tipo=-1, monto, NULL) retiro,
IF(tipo=1,@dispo:=@dispo + monto,@dispo:=@dispo - monto) disponible FROM movimiento
WHERE movimiento.cuentaid='CAJA-001' AND movimiento.fecha BETWEEN '2018-11-01' AND '2018-11-01';
movimientoId fecha descripcion clienteid deposito retiro disponible
------------ -------- ----------------- -------- --------- ------- ------------
1 01/11/18 Saldo Inicial 41422102 10000.00 (NULL) 10000.00
2 01/11/18 Compra Al Contado 003 (NULL) 5000.00 5000.00
3 01/11/18 Compra Al Contado 003 (NULL) 100.00 4900.00
4 01/11/18 Compra Al Contado 41422102 (NULL) 100.00 4800.00
Now I want to include the nombre
of the client instead of the clienteId
, but this is where the query returns unordered records:
SET @dispo=0;
SELECT movimientoId, DATE_FORMAT(fecha, '%d/%m/%y') fecha, descripcion, nombre,
IF(tipo=1, monto, NULL) deposito, IF(tipo=-1, monto, NULL) retiro,
IF(tipo=1,@dispo:=@dispo + monto,@dispo:=@dispo - monto) disponible
FROM movimiento INNER JOIN cliente ON movimiento.clienteid=cliente.clienteid
WHERE movimiento.cuentaid='CAJA-001' AND movimiento.fecha BETWEEN '2018-11-01' AND '2018-11-01';
movimientoId fecha descripcion nombre deposito retiro disponible
------------ -------- ----------------- ------- -------- ------- ------------
2 01/11/18 Compra Al Contado paul (NULL) 5000.00 -5000.00
3 01/11/18 Compra Al Contado paul (NULL) 100.00 -5100.00
1 01/11/18 Saldo Inicial sistema 10000.00 (NULL) 4900.00
4 01/11/18 Compra Al Contado sistema (NULL) 100.00 4800.00
Messy for the column MovimientoId
or at least that I thought, since I could see that the records were sorted according to the PK
of the client table clienteId
. I already explained that the ordering of records by default depends on the engine, I did it with ORDER BY movimientoId
and if it comes out in order but the results of the column depósito
, retiro
and disponible
are calculated wrong. What form can my query be? Thank you. PS: the field 'client' in both tables is of type VARCHAR (11) although I change it to int
and I do not change the results