1

这个查询有什么问题?

SELECT *, (SELECT COUNT(*)
FROM
(
    SELECT NULL
    FROM words
    WHERE project=projects.id
    GROUP BY word
    HAVING COUNT(*) > 1
) T1) FROM projects

MySQL 在“where 子句”中返回 1054 未知列“projects.id”

谢谢

4

3 回答 3

8

这行得通吗?

SELECT *, (SELECT COUNT(*)
    FROM words
    WHERE words.project=projects.id) as pCount
 FROM projects
于 2010-10-31T13:31:55.513 回答
2

看起来您正在尝试为每个项目计算多次出现的单词数。

您可以为所有项目运行子查询,然后使用 JOIN 从项目表中获取其余数据:

SELECT projects.*, COUNT(word) AS cnt
FROM projects
LEFT JOIN (
        SELECT project, word
        FROM words
        GROUP BY project, word
        HAVING COUNT(*) > 1
) T1
ON T1.project = projects.id
GROUP BY projects.id

结果:

身份证号码
1 0
2 1
3 2

测试数据:

CREATE TABLE projects (id INT NOT NULL);
INSERT INTO projects (id) VALUES (1), (2), (3);

CREATE TABLE words (project INT NOT NULL, word VARCHAR(100) NOT NULL);
INSERT INTO words (project, word) VALUES
(1, 'a'),
(2, 'a'),
(2, 'b'),
(2, 'b'),
(3, 'b'),
(3, 'b'),
(3, 'c'),
(3, 'c');
于 2010-10-31T13:33:47.570 回答
2

您的内部子查询对外部查询一无所知,因此该projects表不可用。

于 2010-10-31T13:26:30.050 回答