【问题标题】:MySql query help : joints with sums and countsMySql 查询帮助:带有总和和计数的关节
【发布时间】:2009-03-26 21:41:38
【问题描述】:

我有这个数据库结构:

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)错误。知道为什么吗?

【问题讨论】:

    标签: mysql join


    【解决方案1】:

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

    Enita non sunt multiplicanda praeter necessitatem

    (拉丁语,“实体不得在必要时增加”)

    您的表 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;
    

    【讨论】:

    • 完美!你甚至帮助我了解了我从请求中得到的数字。那我会做4个请求!尝试在几个小时内一次完成所有事情……:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-18
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    相关资源
    最近更新 更多