错误的SQL查询:#1111时-使用SUM方法-无效使用组函数

时间:2019-04-01 07:26:29

标签: mysql sql mysqli

我正在使用MySQL,这是我的查询。 该查询工作正常,但获得多行金额。

SELECT tcc.entry_fees*COUNT(tccc.match_contest_id) as amount 
FROM `tbl_cricket_customer_contests` tccc 
LEFT JOIN tbl_cricket_contest_matches tccm on(tccm.id=tccc.match_contest_id) 
LEFT JOIN tbl_cricket_contests tcc ON (tcc.id=tccm.contest_id) 
WHERE tccc.customer_id = 9 GROUP BY tccc.match_contest_id

使用SUM方法时比出现错误 MySQL说:

1111-无效使用组功能

SELECT SUM(tcc.entry_fees*COUNT(tccc.match_contest_id)) as amount 
FROM `tbl_cricket_customer_contests` tccc 
LEFT JOIN tbl_cricket_contest_matches tccm on(tccm.id=tccc.match_contest_id) 
LEFT JOIN tbl_cricket_contests tcc ON (tcc.id=tccm.contest_id) 
WHERE tccc.customer_id = 9 GROUP BY tccc.match_contest_id

3 个答案:

答案 0 :(得分:2)

您不能在另一个函数上使用聚合函数。您需要分开查询:

SELECT SUM(amount) As Amount
FROM 
(
    SELECT tcc.entry_fees*COUNT(tccc.match_contest_id) as amount 
    FROM `tbl_cricket_customer_contests` tccc 
    LEFT JOIN tbl_cricket_contest_matches tccm on(tccm.id=tccc.match_contest_id) 
    LEFT JOIN tbl_cricket_contests tcc ON (tcc.id=tccm.contest_id) 
    WHERE tccc.customer_id = 9 GROUP BY tccc.match_contest_id
) As DT

更新

正如我在评论中所写,我不是MySql专家,但是我认为这是您正在寻找的东西。
注意,我已经在外部查询中注释了group by子句。

SELECT tc.*,
    (
        SELECT SUM(amount) As Amount
        FROM 
        (
            SELECT tcc.entry_fees*COUNT(tccc.match_contest_id) as amount 
            FROM `tbl_cricket_customer_contests` AS tccc 
            LEFT JOIN tbl_cricket_contest_matches AS tccm on(tccm.id=tccc.match_contest_id) 
            LEFT JOIN tbl_cricket_contests AS tcc ON (tcc.id=tccm.contest_id) 
            WHERE tccc.customer_id = tc.id GROUP BY tccc.match_contest_id
        ) As DT
    ) as spendamount
FROM `tbl_customers` As tc
WHERE tc.`is_deleted` = 'N' 
-- Do you really need that group by here? GROUP BY tc.`id` 
ORDER BY tc.`spendamount` DESC

答案 1 :(得分:1)

如果要总额,请不要嵌套聚合函数并删除group by

SELECT SUM(tcc.entry_fees) as amount 
FROM tbl_cricket_customer_contests tccc JOIN
     tbl_cricket_contest_matches tccm
     ON tccm.id = tccc.match_contest_id JOIN
     tbl_cricket_contests tcc
     ON tcc.id = tccm.contest_id
WHERE tccc.customer_id = 9;

我也将LEFT JOIN更改为JOIN。您正在对最后一张表中的值求和,因此只有匹配的行才占总和。

答案 2 :(得分:0)

尝试:

GROUP BY tcc.entry_fees

代替

GROUP BY tccc.match_contest_id

您需要GROUP BY使用不包含聚合的字段。 GROUP BY将对您所有的entry_fees进行分组,并为每组计数match_contest_id