MySQL中where子句和别名的问题

时间:2011-07-14 14:30:04

标签: mysql sql

这个mysql查询出了什么问题:

select * 
    from tpa as t1 
    where ( select count(*) 
                from tpa as t2 
                where t1.id = t2.id )

错误:

Error Code: 1054. Unknown column 't1.id' in 'field list'

2 个答案:

答案 0 :(得分:0)

我认为,正如Cfreak在评论中指出的那样,别名在子查询中是不可见的。

我认为您忘记为count(*)结果指定某些条件等于某个数字(或其他条件):

select * from tpa as t1 
where
(
select count(*) from
(
select * from tpa
)
as t2
where t1.id = t2.c_id 
) = 1

使用您喜欢的任何数字条件更改“= 1”,否则这将是重写这个更简单的查询的愚蠢方式:

select distinct * from tpa

: - )

答案 1 :(得分:0)

select id, count(*) from tpa as t1
group by id

/*If you need a certain count.. add-*/
having count(*) > 2

在任何一种情况下都不需要使用子查询。