2016-08-17 136 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

相关问题