gpt4 book ai didi

MySql 查询帮助 : joints with sums and counts

转载 作者:行者123 更新时间:2023-11-30 21:24:29 25 4
gpt4 key购买 nike

我有这样的数据库结构:

TBL_A  |  TBL_B  |  TBL_C  |  TBL_D  | TBL_E
-------+---------+---------+---------+----------
id | id_tbla | id_tbla | id_tbla | id
name | id_user | id_user | id_user | name_tbla
... | is_bool | | weight | id_user

这是我要实现的目标:

SELECT 
a.id,
a.name,
b.is_bool,
count(c.id_user) AS nb_views,
sum(d.weight) AS total_weight,
count(distinct e.id_user) AS distinct_users,
FROM TBL_A AS a
LEFT JOIN (TBL_B AS b) on (b.id_tbla = a.id)
LEFT JOIN (TBL_C AS c) on (c.id_tbla = a.id)
LEFT JOIN (TBL_D AS d) on (d.id_tbla = a.id)
LEFT JOIN (TBL_E AS e) on (e.name_tbla = a.name)
where a.id = 1 and e.id_user = 1

执行了查询,但结果(nb_views、total_weight、distinct_users)是错误的。知道为什么吗?

最佳答案

您试图在一个查询中计算太多聚合。

Enita non sunt multiplicanda praeter necessitatem

(Latin, "entities are not to be multiplied beyond necessity")

您的表 B、C、D 和 E 已生成 Cartesian Products互相反对。假设A匹配中的给定行:

  • B 中 3 行
  • C 中的 6 行
  • D 中 4 行
  • E 中的 1 行

结果中的总行数为 3 * 6 * 4 * 1 = 72 行。所以你的 count(c.id_user) 是它应该的 12 倍,你的 sum(d.weight) 是它应该的 18 倍,等等。

最简单的补救措施是在单独的查询中计算这些聚合中的每一个:

SELECT a.id, a.name, COALESCE(b.is_bool, FALSE) AS is_bool
FROM TBL_A AS a LEFT JOIN TBL_B AS b ON (b.id_tbla = a.id)
WHERE a.id = 1;

SELECT a.id, COUNT(c.id_user) AS nb_views
FROM TBL_A AS a LEFT JOIN TBL_C AS c ON (c.id_tbla = a.id)
WHERE a.id = 1;

SELECT a.id, SUM(d.weight) AS total_weight,
FROM TBL_A AS a LEFT JOIN TBL_D AS d ON (d.id_tbla = a.id)
WHERE a.id = 1;

SELECT a.id, COUNT(DISTINCT e.id_user) AS distinct_users,
FROM TBL_A AS a LEFT JOIN TBL_E AS e
ON (e.name_tbla = a.name AND e.id_user = 1)
WHERE a.id = 1;

关于MySql 查询帮助 : joints with sums and counts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/687664/

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