寻找从不同表中提取计数的最有效方法

时间:2015-05-26 23:09:05

标签: mysql

我有以下表格,每个表格中都有给定的数字或行。

Table         Rows     Purpose
product       1695     Holds all products we sell
user_product  25,564   Ties users and products together (purchased products)
instructor    47       Holds all instructor information
location      220      Holds all location information

我需要知道前50行的信息如下:

Table         Column                    Relationship With Table "product"
product       product_id             
product       product_name
user_product  Count(user_product_id)    product_id
instructor    instructor_full_name      instructor_id
location      location_name             location_id

请注意,每个产品都有一个位置,但每个产品可能没有教师或与之绑定的任何user_products。

以下sql语句有效,但拉结果需要很长时间。

SELECT COUNT(user_product_id) as products_sold, product.product_id, product.product_name, location.location_name, instructor.instructor_full_name 
FROM product 
LEFT JOIN instructor ON product.instructor_id = system_instructor.instructor_id 
LEFT JOIN user_product ON product.product_id =  user_product.product
INNER JOIN location ON product.location_id = location.location_id 
GROUP BY product_id 
LIMIT 0, 50

期望的结果:

product_id    product_name     products_sold   instructor_full_name   location_name
1             System Risks     356             Tim Tom                room 1004
2             Planning Ahead   42              Bill Bob               room 2025

我想问题是这是提取这些数据最有效的方法吗?遗憾的是,我发现运行它的一种更快的方法是逐行拉出购买产品的数量,因为它循环查询而不是调用一个大的查询

1 个答案:

答案 0 :(得分:0)

从产品中选择COUNT()和必要字段作为子查询,然后执行连接:

    SELECT *
    FROM
    ((SELECT COUNT(user_product_id) as products_sold, product_id)
    FROM user_product 
    GROUP BY product_id 
    LIMIT 0, 50) as productsCounted
JOIN product ON product.product_id = productsCounted.product_id) as counted_and_id
    LEFT JOIN instructor ON counted_and_id.instructor_id = system_instructor.instructor_id 
    LEFT JOIN user_product ON product.product_id =  counted_and_id.product_id
    INNER JOIN location ON counted_and_id.location_id = location.location_id ;

否则,您在聚合之前进行连接,并生成一个巨大的表。