此查询有什么问题?
SELECT *, (SELECT COUNT(*)
FROM
(
SELECT NULL
FROM words
WHERE project=projects.id
GROUP BY word
HAVING COUNT(*) > 1
) T1) FROM projects
MySQL在'where子句'
中返回1054 Unknown列'projects.id'由于
答案 0 :(得分:6)
这有用吗?
SELECT *, (SELECT COUNT(*)
FROM words
WHERE words.project=projects.id) as pCount
FROM projects
答案 1 :(得分:2)
您的内部子查询对外部查询一无所知,因此projects
表不可用。
答案 2 :(得分: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
结果:
id cnt 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');