Group results mysqli

1

I'm trying to group results from a table so that I can add all the quantities of the same model, but I do not quite understand how it works.

I will try to explain what I need to see if I am able: I have 2 tables that are called orders and other orders line one with two fields with the same value in each one. In Orders it is called id and in line_orders it is called request and it is a numeric field. In orders is a unique number, in orders_line there can be several results that have the same value (used to add several records to an order.). On the other hand in orders I keep a status record that is called "status" where I save the state that has the order. Within "order_line" I keep a field called "quantity" and another one called "idcosa" that links to another table and gives me the field "size", "color", "sex", "material" and "season" "of that article.

The fact is that I would like to know the sum of the number of articles I have of all the orders that have the * state 1 in which idcosa is the same

* State = orders table * idcosa = table Line_Orders

Right now I have this code:

$CPedido = Consulta_Dinamica("Array","*","Pedidos","'estado' = '1' ");
 foreach($CPedido as $DPedido) { //creo un array con el listado de pedidos
$CDPedido = Consulta_Dinamica("Simple","*","Pedidos","'id' = '".$DPedido["id"]."' ");
$CLineasPedido = Consulta_Dinamica("Array","*","Pedidos_Linea","'idpedido' = '".$DPedido["id"]."' ORDER BY 'lineanum' ASC "); 
}

But I only get the details of an order and apart does not add anything (something obvious since I only have the data of a single order and there is nothing to add).

Could you help me out? I'm a bit lost the way I could do it. Thank you very much for your help.

To save the id of the used orders I have used this code:

$implode_arr = array();
$CidPedidos = mysqli_query($Conectar, 'SELECT id  FROM 'Pedidos' WHERE 'empresa' = '.$_SESSION['Empresa_Id'].' AND 'estado' = 1');
while($row = mysqli_fetch_array($CidPedidos)) { $implode_arr[] = $row['id']; }
$Idpedidos = implode(',', $implode_arr);

I do not know if there will be a way to do this implode directly in the main query.

    
asked by Killpe 12.11.2017 в 13:34
source

1 answer

1

You need a SELECT multi table and the use of GROUP BY which serves to group the result set by one or more columns, in this case only a idpedido .

SELECT COUNT(C.idpedido) cantidad, C.concepto FROM Pedidos_Linea C, Pedidos O WHERE (C.idpedido = O.id AND O.estado = 1) GROUP BY c.idpedido;
  

Maybe you may have written a wrong column or table name by mistake, I did it in memory please check.

UPDATE

At the request of the user who needs to show the order ID.

SELECT O.id, COUNT(C.idpedido) cantidad, C.concepto FROM Pedidos_Linea C, Pedidos O WHERE (C.idpedido = O.id AND O.estado = 1) GROUP BY c.idpedido;
    
answered by 12.11.2017 / 20:48
source