0

我试图用 s 在几个表中进行计数JOIN,但是当我做了几个JOINs时, COUNTs 被错误地计算了。

基本上我有 4 个表,命名为:

  1. predective_search
  2. predective_to_product
  3. predective_to_category
  4. predective_to_manufacturer

我想计算表 predective_search 中具有相同 id 的产品、类别和制造商的总数。

这是我的代码:

SELECT * , 
    COUNT(pp.predictive_id) AS total_products, 
    COUNT(pc.predictive_id) AS total_categories, 
    COUNT(pm.predictive_id) AS total_manufacturers 
FROM predictive_search ps 
LEFT JOIN predictive_to_product pp ON (ps.predictive_id = pp.predictive_id) 
LEFT JOIN predictive_to_category pu ON (ps.predictive_id = pc.predictive_id) 
LEFT JOIN oc_predictive_to_manufacturer pm ON (ps.predictive_id = pm.predictive_id)    
GROUP BY ps.predictive_id

GROUP BY我认为也是需要的。我坚持这一点,因为我没有办法做到这一点

4

1 回答 1

0
SELECT 
    ps.*,
    agg_pp.total_products,
    agg_pc.total_categories,
    agg_pm.total_manufacturers
FROM predictive_search ps 
LEFT JOIN ( 
        SELECT pp.predictive_id, COUNT(*) AS total_products
        FROM predictive_to_product pp 
        GROUP BY pp.predictive_id 
    ) agg_pp ON ps.predictive_id = agg_pp.predictive_id
LEFT JOIN ( 
        SELECT pc.predictive_id, COUNT(*) AS total_categories
        FROM predictive_to_category pc 
        GROUP BY pc.predictive_id 
    ) agg_pc ON ps.predictive_id = agg_pc.predictive_id
LEFT JOIN ( 
        SELECT pm.predictive_id, COUNT(*) AS total_manufacturers
        FROM predictive_to_category pm 
        GROUP BY pm.predictive_id 
    ) agg_pm ON ps.predictive_id = agg_pm.predictive_id
于 2013-11-05T16:43:34.287 回答