WHERE子句导致Mysql查询中出现语法错误

时间:2014-03-27 13:01:29

标签: mysql sql

考虑(银行)的表格:

帐户

enter image description here

客户

enter image description here

我想返回拥有更多客户端的所有客户端ID 银行中的一个帐户

我的建议:

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子句会导致语法错误。为什么?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

答案 2 :(得分:-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;