Not all fields in my table are created

-1

I am trying to make a CREATE TABLE that results from the query of 2 different tables. What I want to know is the number of products that each user has. Some help? Thank you very much in advance.

            usuarios
            --------
            id | nombre_usuario 

            productos 
            ---------
            id_producto | id_usuario | nombre_producto | tipo_producto      
    
asked by Matrix 05.11.2017 в 19:33
source

1 answer

0

If we have these 2 tables ...:

            usuarios
            --------
            id | nombre_usuario 

            productos 
            ---------
            id_producto | id_usuario | nombre_producto | tipo_producto 

.. And we want to know how many products each user has, we could solve it in the following way:

            SELECT usuarios.nombre_usuario, COUNT(*) 
            AS contar FROM  usuarios 
            INNER JOIN productos ON usuarios.ID = productos.id_usuario 
            GROUP BY productos.id_usuario 

If we want to obtain the result of the previous query imagining that the product type is "others", we would add WHERE... , like this:

            SELECT usuarios.nombre_usuario, COUNT(*) 
            AS contar FROM  usuarios 
            INNER JOIN productos ON usuarios.ID = productos.id_usuario 
            WHERE tipo_producto = 'otros'
            GROUP BY productos.id_usuario

Finally, if we want to create a table with the results of that query, we just have to add CREATE TABLE nombre_de_la_tabla in front of the query. Greetings and I hope my question-answer is useful.

    
answered by 09.11.2017 / 16:43
source