2016-08-17 49 views
0

首先,我想聲明在編寫SQL查詢方面仍然是一個新手。我徹底地搜索了關於這個錯誤的答案,並且我得到了很多答案,但沒有一個看起來有幫助,或者我會說我真的不知道如何將解決方案應用於我的答案。SQL MySQL錯誤(1241)操作數應該包含1列

這是我的挑戰,我有一個應用程序表,它存儲具有某些唯一列(例如dl_number,parent_id,person_id)的申請人記錄。 parent_id使用他/她的第一條記錄來記錄個人申請人歷史記錄,並且每個申請人都有唯一的dl_number,但由於某些原因,某些申請人的dl_number不是唯一的,因此需要用改變dl_number(s)。

下面是SQL查詢,即得到[sql error(1241)操作數應該包含1列]錯誤。

SELECT id,application_id,dl_number,surname,firstname,othername,birth_date,status_id,expiry_date,person_id,COUNT(DISTINCT(dl_number,parent_id,birth_date)) AS NumOccurrences 
FROM tbl_dl_application 
WHERE status_id > 1 
GROUP BY dl_number,parent_id,birth_date 
HAVING NumOccurrences > 1 

請幫助解決這個問題,或者更好的解決方法。

Sample table and expected result

+0

添加一些示例表數據和預期結果! – jarlh

+0

您按2個字段分組並選擇了更多。 – Whencesoever

+1

可能導致這個'COUNT(DISTINCT(dl_number,parent_id,birth_date))' –

回答

0

DISTICT是不是真的要使用這樣的功能。 您可以只做SELECT DISTICT column1, column2 FROM table以獲得唯一的行,或者類似地SELECT column, count(DISTINCT anothercolumn) FROM table GROUP BY column以獲取組中的唯一行。

問題,據我所知:你在你的表中尋找重複。重複被定義爲具有相同的這3列的值:dl_n‌​umber,parent_idbirth‌​_date

我還假設id是您的表中的主鍵。如果不是,請將t2.id <> t.id條件替換爲唯一標識您的行的條件。

如果你只是想知道什麼是重複的組,這應該工作:

SELECT dl_n‌​umber, parent_id, birth‌​_date, count(*) as NumOccurences -- You can only add aggregation functions here, not another column unless you group by it. 
FROM tbl_dl_application t 
WHERE status_id > 1 -- I don't know what this is but it should do no harm. 
GROUP BY dl_n‌​umber, parent_id, birth‌​_date 
HAVING count(*)>1 

但是,如果你想知道每個重複行的細節,這個查詢會給你:

SELECT * 
FROM tbl_dl_application t 
WHERE 
    status_id > 1 -- I don't know what this is but it should do no harm. 
    AND EXISTS (
     SELECT 1 
     FROM tbl_dl_application t2 
     WHERE 
      t2.dl_number = t.dl_number 
      AND t2.parent_id = t.parent_id 
      AND t2.birth_date = t.birth_date 
      AND t2.id <> t.id 
    ) 
ORDER BY dl_n‌​umber, parent_id, birth‌​_date, id; -- So you have your duplicates nicely next to each other. 

如果我誤解了你的目標,或者詢問解決方案是否不夠清楚,請進一步解釋。

0
**You have to use only one column while use to DISTINCT function. You used this three field dl_number,parent_id,birth_date. Just use 1 filed from these 3. Then query will run.** 

例如,

SELECT id,application_id,dl_number,surname,firstname,othername,birth_date,status_id,expiry_date,person_id,COUNT(DISTINCT(parent_id)) AS NumOccurrences 
FROM tbl_dl_application 
WHERE status_id > 1 
GROUP BY dl_number,parent_id,birth_date 
HAVING NumOccurrences > 1 
+0

不正確。請參閱http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_count-distinct – jirka

相關問題