【问题标题】:SQL Query join with a count and avg from another tableSQL Query join 与另一个表的计数和平均值
【发布时间】:2013-04-25 05:05:51
【问题描述】:

实际上,数学似乎并没有加起来。

这是我正在使用的查询和我尝试访问的 2 个表(包含所有真实数据)。

SQL 中的这个查询将Steve Smith 拉到amount 的 27 和 27 计数。它应该是 17。在同一个查询中,它显示 John Smith 有 4 个总和和 2 个 amount 计数。

SELECT
user.*,
IFNULL(SUM(collection.amount), 0) AS usertotal,
COUNT(collection.amount) AS userunique
FROM user
LEFT JOIN collection
ON user.id = collection.userid
GROUP BY collection.amount`

表 1(命名为 user):

id | firstname | lastname | username | email
1  | Steve     | Smith    | SteveS   | Steve@Smith.com
2  | John      | Smith    | JohnSmith| John@Smith.com

表2(命名为collection):

id|userid|carid |amount
1   1   74  1
10  2   130 1
11  2   48  1
12  2   414 1
13  2   415 1
14  2   66  1
15  2   404 1
16  2   57  2
17  2   331 1
18  2   264 1
19  2   325 1
20  2   51  2
21  2   185 1
24  1   168 1
25  1   11  1
26  1   315 1
27  1   51  1
28  1   210 1
29  1   433 1
30  1   434 1
31  1   460 1
32  1   75  1
33  1   238 1
34  1   226 1
35  1   396 1
36  1   174 1
37  1   12  1
38  1   328 1
39  1   4   1



id| UN | Amount
1 | 4  | 457
2 | 4  | 28
3 | 2  | 234
4 | 1  | 235
5 | 2  | 1

我需要一个查询来获取用户名的完整列表,以及 user.id 和 collection.UN 之间的内部连接(在数量列上使用 sum 和 count)

我不知道 SQL 查询,这辈子都弄不明白。帮忙?

谢谢,

【问题讨论】:

    标签: php mysql sql codeigniter


    【解决方案1】:
    SELECT 
      user.UN as username, 
      IFNULL(SUM(collection.Amount), 0) AS sum,
      COUNT(collection.Amount) AS count
    FROM user
    LEFT JOIN collection
      ON user.id = collection.UN
    GROUP BY user.id
    

    您说您想使用INNER JOIN,但这不会显示那些在集合表中没有记录的用户。所以我改为使用LEFT JOIN,以便返回整个用户列表,如果他们没有任何数量,他们的数量将是0。

    【讨论】:

    • 数学实际上并没有加起来。我会更新我原来的帖子并解释一下。
    • SUM 工作正常吗?对于COUNT 的问题,我猜是因为它还计算了空值。我现在会着手修复。
    • @AndrewWilson 啊,我现在明白了。问题在于您的 GROUP BY 声明。它应该是GROUP BY user.id 而不是collection.amount。再试一次:)
    • 就是这样!我想我不明白 GROUP BY,我今天早上需要研究一下 :)
    【解决方案2】:

    使用这个:

        select u.* , c.total_amount from users as u 
    inner join (select un, sum(amount) total_amount 
    from collection group by un)  c on u.id = c.un
    

    PHP 查询:

     $q = "select u.* , c.total_amount from users as u 
    inner join (select un, sum(amount) total_amount 
    from collection group by un)  c on u.id = c.un";    
        $result = $this->db->query($q);
        //echo $this->db->last_query();
    

    【讨论】:

    • 我认为它应该是“on user.id=collection.UN”而不是“user.id=collection.id”。
    • 我应该相信,但即使我用上面的代码改变它,我也会得到:Unknown column 'c.userid' in 'on clause'
    • @veekay 在查询中使用了别名。好的,只需将 u 替换为用户(表 1 名称),将 c 替换为集合(表 2 名称)并检查结果。
    • 它在我的本地工作。 @Andrew 尝试根据您的要求进行调整。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-19
    • 1970-01-01
    • 2012-11-16
    相关资源
    最近更新 更多