0

收到错误消息 [Err] 1060 - Duplicate column name 'id'

SELECT c.id, c.name, COUNT(all.id) 'All', 
       COUNT(unanswered.id) 'Unanswered',
       COUNT(unchecked.id) 'Unchecked'
FROM courses c
INNER JOIN courses-lessons cl ON c.id = cl.cid
INNER JOIN questions all ON cl.id = all.lid
INNER JOIN
(
    SELECT * 
    FROM questions
    WHERE id NOT IN (SELECT qid FROM answers)
) unanswered ON cl.id = unchecked.lid
INNER JOIN
(
    SELECT *
    FROM questions q
    INNER JOIN 
    (
        SELECT * 
        FROM answers
        WHERE id NOT IN (SELECT aid FROM answer_chk_results)
    ) a ON q.id = a.qid 
) unchecked ON cl.id = unchecked.lid
GROUP BY c.id, c.name

我错过了什么?找不到问题所在。

更新

数据库结构

https://docs.google.com/open?id=0B9ExyO6ktYcOenZ1WlBwdlY2R3c

4

3 回答 3

0

您的问题和答案表都有 id 列。当您执行 SELECT * 时,您将获得两者的 id 列。尝试在 SELECT 中指定您需要的列,而不是使用 *

有关类似问题,请参见此处:SQL Duplicate column name error

于 2012-08-29T16:18:51.747 回答
0

不确定它是否是您的问题的一部分,但您不应将表别名为“all”,因为它是 MySQL 关键字。

于 2012-08-29T16:19:56.690 回答
0

很可能在您查询的这一部分:

SELECT *
FROM questions q
INNER JOIN 
(
    SELECT * 
    FROM answers
    WHERE id NOT IN (SELECT aid FROM answer_chk_results)
) a ON q.id = a.qid 

外部查询将有两个名为 的字段id,您应该指定所需的id字段。SELECT *此外,您应该调出您需要的字段,而不是使用。

ALL也是一个保留字,我会考虑更改该别名或`在其周围使用反引号。

根据您的表结构,它看起来像您想要的:

SELECT c.id, 
    c.name, 
    COUNT(allq.id) 'All', 
    COUNT(unanswered.id) 'Unanswered',
    COUNT(unchecked.id) 'Unchecked'
FROM courses c
INNER JOIN courses-lessons cl 
    ON c.id = cl.cid
INNER JOIN questions allq 
    ON cl.id = allq.lid
INNER JOIN
(
    SELECT q.id, a.qid, q.lid
    FROM questions q
    INNER JOIN 
    (
        SELECT id, qid
        FROM answers
        WHERE id NOT IN (SELECT aid FROM answer_chk_results)
    ) a 
        ON q.id = a.qid 
) unchecked 
    ON cl.id = unchecked.lid
INNER JOIN
(
    SELECT id
    FROM questions
    WHERE id NOT IN (SELECT qid FROM answers)
) unanswered 
    ON cl.id = unchecked.lid
GROUP BY c.id, c.name
于 2012-08-29T16:20:07.573 回答