错误SQL查询:使用SUM方法,当#1054 - 'where子句'中的未知列'tbl_customers.id'时

问题描述 投票:0回答:3

当我们表示客户ID而非收到错误#1054 - 'where子句'中的未知列'tbl_customers.id'实际问题是每个派生表必须有自己的别名。

喜欢这个查询以下。

SELECT tbl_customers.*,(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 = tbl_customers.id GROUP BY tccc.match_contest_id
) As DT) as spendamount
FROM (`tbl_customers`) 
WHERE `tbl_customers`.`is_deleted` = 'N' 
GROUP BY `tbl_customers`.`id` 
ORDER BY `spendamount` DESC

下面的表关系结构在查询之后。

enter image description here

mysql sql mysqli
3个回答
0
投票

您在子查询中使用tbl客户的地方,您无权访问它。你只需要加入而不是使用where:

SELECT tbl_customers.*,(SELECT SUM(amount) As Amount
FROM 
(
    SELECT tcc.entry_fees*COUNT(tccc.match_contest_id) as amount 
    FROM `tbl_cricket_customer_contests` tccc 
    JOIN `tbl_customers` ON (tccc.customer_id = tbl_customers.id)
    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) 
    GROUP BY tccc.match_contest_id
) As DT) as spendamount
FROM (`tbl_customers`) 
WHERE `tbl_customers`.`is_deleted` = 'N' 
GROUP BY `tbl_customers`.`id` 
ORDER BY `spendamount` DESC

0
投票

我不确定这对MySql是否有效,但是尝试将派生表从子查询移动到from子句(注意:我已经更改了派生表的列,但我认为它应该没问题案件):

SELECT tbl_customers.*,(SELECT SUM(amount) As FROM DT) as spendamount
FROM `tbl_customers`
INNER JOIN
(
    SELECT tccc.customer_id, 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) 
    GROUP BY tccc.customer_id 
) As DT
    ON dt.customer_id = `tbl_customers`.`id` 
WHERE `tbl_customers`.`is_deleted` = 'N' 
GROUP BY `tbl_customers`.`id` 
ORDER BY `spendamount` DESC

0
投票

如果我想要总金额,请不要嵌套聚合函数并通过以下方式删除组:

SELECT tbl_customers.*,(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 = tbl_customers.id ) as spendamount
FROM (`tbl_customers`) 
WHERE `tbl_customers`.`is_deleted` = 'N' 
GROUP BY `tbl_customers`.`id` 
ORDER BY `spendamount` DESC

我还将LEFT JOIN改为JOIN。您要对最后一个表中的值求和,因此只有匹配的行才会对总和产生影响。

© www.soinside.com 2019 - 2024. All rights reserved.