Php SQL查询使用另一个表中的计数和平均值进行联接

Php SQL查询使用另一个表中的计数和平均值进行联接,php,mysql,sql,codeigniter,Php,Mysql,Sql,Codeigniter,事实上,数学似乎不正确 这是我正在使用的查询和我试图访问的2个表(所有真实数据) SQL中的此查询将Steve Smith拉到27和27计数的金额。应该是17岁。在同一个查询中,它显示了John Smith有4个sum和2个count的amount SELECT user.*, IFNULL(SUM(collection.amount), 0) AS usertotal, COUNT(collection.amount) AS userunique FROM user LEFT JOIN col

事实上,数学似乎不正确

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

SQL中的此查询将Steve Smith拉到27和27计数的
金额
。应该是17岁。在同一个查询中,它显示了
John Smith
有4个sum和2个count的
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
):

表2(命名为
集合
):

我需要一个查询来获取整个用户名列表,以及user.id和collection.UN之间的内部联接(sum和count位于amount列)

我不知道SQL查询,我一辈子都搞不懂。帮忙

谢谢

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
您说过要使用
内部联接
,但这不会显示那些在集合表中没有记录的用户。因此,我使用了
LEFT JOIN
,这样将返回整个用户列表,如果没有用户,则其金额的
COUNT
SUM
将为0。

使用以下方法:

    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”。我应该相信,但即使我用上面的代码更改了它,我也会得到:
on子句中的未知列“c.userid”
@veekay在查询中使用了别名。好的,做一件事,用users(表1的名称)替换u,用collection(表2的名称)替换c,然后检查结果@安德鲁试着根据你的要求进行调整。事实上,数学是不正确的。我会更新我原来的帖子并解释一下。
SUM
正常吗?对于
COUNT
的问题,我想这是因为它也计算空值。“我现在就来解决问题。”安德烈·威尔森:啊,我现在明白了。问题在于您的
groupby
语句。它应该是按用户.id进行分组,而不是按集合.amount进行分组。再试一次:)就是这样!我想我不明白GROUP BY,今天早上我需要调查一下:)
    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
 $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();