gpt4 book ai didi

mysql 多次计数和连接返回奇怪的值

转载 作者:行者123 更新时间:2023-11-30 01:04:48 26 4
gpt4 key购买 nike

我尝试使用 JOIN 在多个表中进行计数,但是当我进行多个 JOIN 时,COUNT 出现错误已统计。

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

  1. predictive_search
  2. predictive_to_product
  3. predictive_to_category
  4. predictive_to_manufacturer

我想统计表predecive_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。我陷入困境,因为我没有任何办法做到这一点

最佳答案

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

关于mysql 多次计数和连接返回奇怪的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19794026/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com