2013-05-03 97 views
1

如何在子查詢中引用父查詢列?這裏是我的查詢#1054 - 'where子句'中的未知列'XXXX'

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可見的子查詢?

Thanx in advance

+6

隊友,請使用JOIN。 theres不需要所有這些子查詢。效率低下且存在問題 – ldgorman 2013-05-03 12:47:08

+0

派生表「d」與「用戶」表之間缺少連接條件。這將創建笛卡爾連接。此外,在派生表內使用聚合在標準SQL中是非法的。 MySQL會讓你逃脫 - 但它會返回隨機值:http://rpbouman.blogspot.de/2007/05/debunking-group-by-myths.html – 2013-05-03 12:49:13

回答

2

爲什麼使用子表?您使用聚合函數SUM但沒有GROUP BY語句,我想你可以這樣寫這樣的

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 

A C和B丟失之間的連接,我無法添加,因爲我不知道鑰匙

+2

請格式化您的查詢。這是一個混亂的閱讀。 – 2013-05-03 12:53:45

+0

這項工作幾乎是我想要的結果,是否也有可能獲得表中不存在的所有記錄merchant_responses? – 2013-05-03 13:21:25

+0

@samdev我不明白你的要求 – Nagasaki 2013-05-03 13:32:43

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 

更新 更新查詢

+1

正確的名稱是「* derived * table 「,而不是」臨時表「。 – 2013-05-03 12:50:00

+0

@a_horse_with_no_name - 已更新 – ysrb 2013-05-03 12:50:47

+0

也被稱爲_inline視圖_ – ninesided 2013-05-03 12:59:26

相關問題