不应该存在的“重复的列名”错误

时间:2019-01-14 15:50:18

标签: mysql mariadb mariasql

我正在尝试将数据库从sqlite迁移到mariaDB(我从未使用过),但似乎无法解决这个问题!

当我尝试运行此命令时,我总是得到

"#1060 - Duplicate column name 'id_document'"

以下是查询:

SELECT
  a.id_document AS id_document,
  id_user_associatedDoc,
  id_user_creator,
  stage,
  title,
  goldStandardAnnotationManual,
  count(content) AS answer_count
FROM
  (SELECT * 
  FROM Document join DocumentProject 
  ON Document.id_document = DocumentProject.id_document 
  WHERE DocumentProject.id_project = 2) a
  LEFT JOIN
  (SELECT * 
  FROM Annotation 
  WHERE Annotation.id_project = 2) b 
  ON a.id_document = b.id_document
GROUP BY a.id_document;

我不明白为什么我会出现此错误!你能帮忙吗?

1 个答案:

答案 0 :(得分:1)

此第一个子查询语法返回两个id_document列:

(SELECT *
 FROM Document
   join DocumentProject
   ON Document.id_document = DocumentProject.id_document
 WHERE DocumentProject.id_project = 2) a

解决此问题的快速方法:

SELECT
  a.id_doc /*Change this column as following*/ AS id_document,
  id_user_associatedDoc,
  id_user_creator,
  stage,
  title,
  goldStandardAnnotationManual,
  count(content) AS answer_count
FROM
  (SELECT *, Document.id_document as "id_doc" /*define the first id_document column as a different name*/
  FROM Document
    join DocumentProject 
    ON Document.id_document = DocumentProject.id_document 
  WHERE DocumentProject.id_project = 2) a
  LEFT JOIN
  (SELECT * 
  FROM Annotation 
  WHERE Annotation.id_project = 2) b 
    ON a.id_document = b.id_document
GROUP BY a.id_document;

您还可以预定义要在子查询中返回的列。示例:

(SELECT Document.id_document, Document.column_2, Document.column_3
 FROM Document
   join DocumentProject
   ON Document.id_document = DocumentProject.id_document 
 WHERE DocumentProject.id_project = 2) a

这样,您的外部查询应根据您在子查询中预先定义的内容选择a.id_document,而无需更改外部查询中的任何内容。