简体   繁体   English

用其他表中的特定值对表中的行进行计数

[英]Count rows in table with certain value in other table

I need a quick way to find the Number of items in a table. 我需要一种快速的方法来查找表中的项目数。 The items are linked to an other table. 这些项目链接到另一个表。 Table 1 is products and table 2 is orders. 表1是产品,表2是订单。

Orders contains a paid status (1 or 0). 订单包含已付款状态(1或0)。

Orders table example: 订单表示例:

id paid
1  0
2  1

Products table example: 产品表示例:

id orderid type
1  1       5
2  1       5
3  1       3
4  2       5
5  2       5
6  2       3

Products contains a id (orderid) that refers to the order and a type. 产品包含引用订单和类型的ID(订单ID)。 So i need the number of products where type = 5 and paid = 1 in the orders table. 所以我需要订单表中类型= 5且已付费= 1的产品数量。

What is the best and fastest way to archieve this? 存档的最佳和最快方法是什么?

So I need all the paid products with type 5. The result should be '2'. 因此,我需要所有类型5的付费产品。结果应为“ 2”。

One way is to use a join statement. 一种方法是使用联接语句。 Making some assumptions about your schema, the following should work: 对您的架构进行一些假设,以下方法应该起作用:

SELECT COUNT(p.`id`) FROM `products_table` p
LEFT JOIN `orders_table` o ON p.`orderid` = o.`id`
WHERE o.`paid` = 1
AND p.`type` = 5

you can use join like this, 您可以像这样使用join

SELECT COUNT(*) AS num_rows 
FROM products 
LEFT JOIN orders ON orders.id = products.orderid 
WHERE type = 5 AND paid = 1

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

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