1

您如何在子查询中引用父查询列?这是我的查询

    SELECT 
    c.username, c.staff_of, CONCAT(c.first_name, ' ', c.middle_name, ' ', c.last_name ) AS csr, 
    d.date, d.account, d.total_transaction, d.total_participate, d.total_amount,
    (SELECT COUNT(id) FROM users WHERE created_by = c.username ) AS total_agents
FROM `users` c,   
    (SELECT
          DATE(res_date) AS date, B.res_account AS account,
          COUNT(B.res_id) AS total_transaction,
          COUNT(DISTINCT(B.res_account)) AS total_participate,
          SUM(B.res_amount) AS total_amount
     FROM
          merchant_responses B
     WHERE B.res_account IN (SELECT t.staff_of FROM users t WHERE t.created_by = c.username)
     ) AS d
WHERE c.account_type ='DSO' GROUP BY c.username

这就是我得到的结果

#1054 - Unknown column 'c.username' in 'where clause'

如何使 c.username 在子查询中可见?

提前感谢

4

2 回答 2

3

那不是子查询,它是派生表。

 SELECT 
    c.username, c.staff_of, CONCAT(c.first_name, ' ', c.middle_name, ' ', c.last_name ) AS csr, 
    d.date, d.account, d.total_transaction, d.total_participate, d.total_amount,
    (SELECT COUNT(id) FROM users WHERE created_by = c.username ) AS total_agents
FROM `users` c,   
    (SELECT
          DATE(res_date) AS date, B.res_account AS account,
          COUNT(B.res_id) AS total_transaction,
          COUNT(DISTINCT(B.res_account)) AS total_participate,
          SUM(B.res_amount) AS total_amount
     FROM
          merchant_responses B
     WHERE B.res_account IN (SELECT t.staff_of FROM users t)
     ) AS d
WHERE c.account_type ='DSO' AND d.account = c.staff_of GROUP BY c.username

更新 更新了查询

于 2013-05-03T12:48:06.323 回答
2

为什么使用子表?你使用聚合函数 SUM 但没有分组语句,我认为你可以这样写

    SELECT c.username, 
           c.staff_of, 
           CONCAT(c.first_name, ' ', c.middle_name, ' ', c.last_name ) AS csr, 
           DATE(B.res_date) AS date, 
           B.res_account AS account, 
           COUNT(B.res_id) AS total_transaction, 
           COUNT(DISTINCT(B.res_account)) AS total_participate, 
           SUM(B.res_amount) AS total_amount,
           (SELECT COUNT(id) FROM users WHERE created_by = c.username ) AS total_agents
    FROM `users` c, merchant_responses B
    WHERE B.res_account IN (SELECT t.staff_of FROM users t WHERE t.created_by = c.username) 
    AND c.account_type ='DSO' 
    GROUP BY c.username

c 和 B 之间的连接丢失,我无法添加它,因为我不知道密钥

于 2013-05-03T12:52:19.890 回答