简体   繁体   English

MySql:从另一个表获取产品的名称

[英]MySql: Get name of a product from another table

I have a table named movimiento which stores the amount of pieces sold by productit 我有一个表命名movimiento存储块由卖出金额productit

idProducto  Cantidad
   8878       2
   8897       3
   8878       5
   8878       2
   8897       3
   8878       5
   8878       2
   8897       3
   8878       5

and another table called producto in where I store the product detail 还有另一个称为producto的表,用于存储产品详细信息

idProducto      Nombre
   8878       Tasa Verde
   8897       Tasa Roja

I'm trying to make a query to get the sum of sales by product id, which I have done this : 我正在尝试查询以按产品ID获取销售总额,我已经这样做了:

SELECT idProducto,
   SUM(cantidad) AS c
FROM movimiento
GROUP BY idProducto

and it's working fine, but I'm trying to put in the query result the name of the product based on the name in table producto 并且工作正常,但是我尝试根据表producto的名称在查询结果中放入产品名称

The query below is not working : 下面的查询不起作用:

    select producto.descripcion
from 
(
SELECT movimiento.idProducto,
       SUM(cantidad) AS c
FROM movimiento, producto
GROUP BY movimiento.idProducto
) as rSum
GROUP BY producto.descripcion

an have tried this too, but nothing 一个也尝试过这个,但没有

select descripcion from producto where idProducto in (
   select idProducto, SUM(cantidad) as c
from movimiento
group by idProducto
   )

You should be able to use a JOIN to link the id to the description of the product... 您应该可以使用JOIN将ID链接到产品说明...

SELECT p.descripcion, SUM(m.cantidad) AS c
    FROM movimiento m
    JOIN producto p ON m.idProducto = p.idProducto
    GROUP BY p.descripcion

Below query is not correct, as you are trying to get producto.descripcion from inline view query. 下面的查询不正确,因为您正在尝试从内联视图查询中获取producto.descripcion But that column doesn't exist in your inline view. 但是该列在您的内联视图中不存在。

select producto.descripcion
from 
/* This represents as inline view */
(
SELECT movimiento.idProducto,
       SUM(cantidad) AS c
FROM movimiento, producto
GROUP BY movimiento.idProducto
) as rSum
/* This represents as inline view */
GROUP BY producto.descripcion

I think, what you are looking for is to JOIN the tables and then use GROUP BY on description column, which @Nigel has already shared sample query. 我想,您正在寻找的是JOIN表,然后在description列上使用GROUP BY ,@ Nigel已经共享了示例查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM