2014-03-27 82 views
0

考慮(某銀行)表:WHERE子句導致語法錯誤在MySQL查詢

賬戶

enter image description here

客戶

enter image description here

我想回到一切客戶編號,有多於 的客戶比銀行的一個帳戶

我的建議:

SELECT c.Client_id_number , c.firstName_client , c.lastName_Client , COUNT(a.Account_number) as number_of_accounts 
FROM Clients AS c 
LEFT JOIN Accounts AS a 
ON a.Client_id_number = c.Client_id_number 
GROUP BY Client_id_number 
WHERE number_of_accounts >= 2; 

但在WHERE子句會導致語法錯誤。爲什麼?

+2

'WHERE'必須出現在'集團BY' –

+0

@JohnConde:當我這樣做,我得到'錯誤代碼:1054.'where子句'中的未知列'number_of_accounts' – ron

+0

'where'子句不能取別名。這裏的'number_of_accounts'是一個別名。 – KrazzyNefarious

回答

1
SELECT c.Client_id_number , c.firstName_client , c.lastName_Client , COUNT(a.Account_number) as number_of_accounts 
FROM Clients AS c 
LEFT JOIN Accounts AS a 
ON a.Client_id_number = c.Client_id_number 
GROUP BY Client_id_number 
HAVING COUNT(a.Account_number) >= 2; 

See this for correct SQL clasues order

0
SELECT Account_number, Client_id_Number 
FROM Accounts 
GROUP BY Account_number, Client_id_Number 
having count(*) > 1 
-1

Where子句應該是組之前,

SELECT c.Client_id_number , c.firstName_client , c.lastName_Client , COUNT(a.Account_number) as number_of_accounts 
FROM Clients AS c 
LEFT JOIN Accounts AS a 
ON a.Client_id_number = c.Client_id_number 
WHERE number_of_accounts >= 2  
GROUP BY Client_id_number; 
+0

這會導致:'錯誤代碼:1054.'where子句中的未知列'number_of_accounts' ' – ron

+1

'number_of_accounts'不是表列 – KrazzyNefarious