简体   繁体   English

如何通过一个SQL查询获得产品以及每个产品的购买数量?

[英]How to get products and the number of buys each has with one SQL query?

Buy has a foreign key product_id . Buy有一个外键product_id

So in addition to SELECT * FROM products; 因此除了SELECT * FROM products; we are interested in getting the number of buys each product has. 我们有兴趣获取每种产品的购买数量。

Something along the lines of: 类似于以下内容:

SELECT p.*, COUNT(buy.product_id) FROM product p INNER JOIN buy ON buy.product_id = p.id GROUP BY buy.product_id

should do the trick. 应该可以。

SELECT p.*,COUNT(b.product_id) FROM products p
INNER JOIN buy b ON p.id=b.product_id
GROUP BY b.product_id

Thats about all I can offer with the info you've posted. 那就是我所能提供的所有信息。 Table structure of both would help a ton if the above doesn't work. 如果上述方法不起作用,两者的表结构都会帮助很多。

Join 加入

SELECT Products.*, COUNT(Buy.ID) AS Bought
FROM products
    LEFT OUTER JOIN Buy ON products.ID = Buy.product_id
GROUP BY Buy.product_id

Subquery 子查询

SELECT 
    Products.*, 
    (SELECT COUNT(ID) FROM Buy WHERE product_id = Products.ID) AS Bought
FROM products

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

相关问题 SQL查询以获取每个类别的产品数 - SQL query to get number of products for each category 如何在一个查询中获取值类别和每个类别的计数产品? - How get values categories an count products for each category in one query? 如何编写 SQL 查询(获取所有类别并在每个类别上获取 10 个产品) - How to write SQL Query (Get all Categories and get 10 Products on each Category) SQL 查询:获取每个 state 的天数 - SQL query: Get number of days for each state Sql 查询获取每种类型的最大 id 号的记录 - Sql Query to get the record what has the max id number for each type 如何覆盖PrestaShop的产品类以限制SQL查询中返回的产品数量? - How do I override PrestaShop's products class to limit the number of products returned in an SQL query? 如何创建一个视图来显示客户在 2019 年 4 月从企业购买的商品总数以及 SQL 中的总价? - How Do I create a view that shows the total number of items a customer buys from the business in April 2019 along with the total price in SQL? SQL查询,一对多,每个匹配的计数 - SQL query, one to many, with count number of each match SQL一站式查询多个产品 - SQL Query Multiple Products on One Order SQL通过OFFSET / FETCH获取每个类别的产品 - SQL get products of each category with OFFSET / FETCH
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM