[英]MySQL unknown column using subquery
I receive an error when i execute this query: 执行此查询时收到错误消息:
SELECT
(SELECT count(cp_projeto_view.id) FROM cp_projeto_view WHERE cp_projeto_view.id_projeto = cp_projeto.id AND cp_projeto_view.id_pessoa = 467 LIMIT 1) AS qtde_visualizacoes
FROM cp_projeto
WHERE qtde_visualizacoes = 0
The error is: #1054 - Unknown column 'qtde_visualizacoes' in 'where clause' 错误是: #1054-“ where子句”中的未知列“ qtde_visualizacoes”
Why qtde_visualizacoes does not exists? 为什么不存在qtde_visualizacoes?
Thank you very much! 非常感谢你!
You cannot use a column alias in a where
clause (unless you use a subquery). 您不能在where
子句中使用列别名(除非您使用子查询)。 MySQL has an extension where you can use having
instead: MySQL有一个扩展,您可以在其中使用having
:
SELECT (SELECT count(cp_projeto_view.id)
FROM cp_projeto_view
WHERE cp_projeto_view.id_projeto = cp_projeto.id AND cp_projeto_view.id_pessoa = 467
LIMIT 1
) AS qtde_visualizacoes
FROM cp_projeto
HAVING qtde_visualizacoes = 0
EDIT: 编辑:
The query that you probably want is more like: 您可能想要的查询更像是:
select p.*
from cp_projecto p
where not exists (select 1 from cp_projeto_view pv where pv.id_projeto = p.id and pv.id_pessoa = 467)
This will return all cp_projecto
s that have no matching rows in cp_projeto_view
. 这将返回cp_projecto
中没有匹配行的所有cp_projeto_view
。 Your original query would only return rows with a single column of 0
s, which doesn't make much sense. 您的原始查询只会返回具有0
s单列的行,这没有多大意义。 If you want the count, then do: 如果要计数,请执行以下操作:
select count(*) as cnt
from cp_projecto p
where not exists (select 1 from cp_projeto_view pv where pv.id_projeto = p.id and pv.id_pessoa = 467)
And, for performance, create an index on cp_projeto_view(projeto, id_pessoa)
. 并且,为了提高性能,请在cp_projeto_view(projeto, id_pessoa)
上创建一个索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.