Juan Francisco Gancia Juan Francisco Gancia - 4 months ago 7
MySQL Question

SQL query to find rows where a colum value is equal to the sum of tow other colums in the same row

Hi guys I need to build a SQL query to find rows from a table where a colum value "total cost" is equal to the sum of tow other colums("price","discount") in the same row.

This is my query:

$sql = "SELECT * FROM pedido INNER JOIN clientes ON
pedido.clientes_id=clientes.clientes_id INNER JOIN chofer
ON pedido.chofer_id=chofer.chofer_id WHERE clientes.clientes_nombre
LIKE '%$filtro_nombre%' AND pedido.pedido_fecha LIKE '%$filtro_fecha%'
AND pedido.pedido_costo = SUM(pedido_descuento + pedido_saldo)
ORDER BY pedido_id DESC LIMIT 20 OFFSET $offset";


The query works removing the part of the SUM():

AND pedido.pedido_costo = SUM(pedido_descuento + pedido_saldo)


Example:

$sql = "SELECT * FROM pedido INNER JOIN clientes ON
pedido.clientes_id=clientes.clientes_id INNER JOIN chofer
ON pedido.chofer_id=chofer.chofer_id WHERE clientes.clientes_nombre
LIKE '%$filtro_nombre%' AND pedido.pedido_fecha LIKE '%$filtro_fecha%'
ORDER BY pedido_id DESC LIMIT 20 OFFSET $offset";


I dont really know how to SUM two values in a SQL query.

Answer

SUM is use to calculate the sum of a particular Column not Rows. Therefore the way you are using SUM won't work. For your requirement. Refer the query below

SELECT * 
FROM 
    pedido 
INNER JOIN 
    clientes ON pedido.clientes_id=clientes.clientes_id 
INNER JOIN 
    chofer ON pedido.chofer_id=chofer.chofer_id 
WHERE 
    clientes.clientes_nombre LIKE '%$filtro_nombre%' 
AND 
    pedido.pedido_fecha LIKE '%$filtro_fecha%' 
AND 
    pedido.pedido_costo = (pedido_descuento + pedido_saldo)
ORDER BY pedido_id 
DESC LIMIT 20 OFFSET $offset";
Comments