代码之家  ›  专栏  ›  技术社区  ›  Carson Myers

在MySQL where子句中使用生成的列

  •  2
  • Carson Myers  · 技术社区  · 15 年前

    如果我有疑问,例如:

    select column1, (
        select count(*) from table2
    ) as some_count
    from table1
    where column1 = 'foo'
    

    我可以用 column1 在where子句中,但是如果我尝试添加

    and some_count > 0
    

    然后我得到一个错误 some_count 不存在。在where子句中如何使用它?

    2 回复  |  直到 15 年前
        1
  •  14
  •   zerkms    15 年前

    HAVING

    select column1, (
        select count(*) from table2
    ) as some_count
    from table1
    HAVING some_count > 0
    
        2
  •  3
  •   OMG Ponies    15 年前

    按原样,唯一的方法是使用派生表:

    SELECT x.*
      FROM (select column1, 
                   (select count(*) from table2) as some_count
              from table1
             where column1 = 'foo') x
     WHERE x.some_count > 0
    

    some_count 是否要为返回的每一行返回相同的值?