开发者

Defining aliases in a statistical query

I need to do:

SELECT COUNT(*)
  FROM some_table
 WHERE someAlias1 = someValue1 
   AND someAlias2 = someValue2;

someAlias is an alias for a column in some_table. In my case I can't name the columns directly; I need to use aliases.

The issue is that I only know about defining aliases inside the select clause which I don't see how I can do in this case.

Is there a way to 开发者_开发技巧accomplish what I need in this case?

edit: Why do I need aliases? I'm building a query from alternative parts, and the condition above applies to different columns from different tables, but with the same logical role. So I need a way to relate to different alternative columns with the same name.

I will appreciate if you answer this question only if you know an answer, even if you don't understand why may I need an alias


You could do a nested SELECT statement then draw the count out from the inner query, I don't really see a way to escape using the column names

SELECT COUNT(*) 
  FROM(
        SELECT col1 as someAlias1, 
               col2 as someAlias2
        FROM   some_table
        WHERE  someAlias1 = someValue1
        AND    someAlias2 = someValue2
       ) as inner


I can't figure out a scenario where you can't name the columns directly. If the column name is duplicated, prepend the table name:

WHERE someTable1.someColumn1 = someValue1

If the column name is a reserved keyword or contains spaces, quote it:

WHERE `some Column1` = someValue1

You can even combine both:

WHERE someTable1.`some Column1` = someValue1


Why do you need to use aliases? The only reason to use aliases in your query would be for re-use in e.g. an "having" clause, like:

select count(*)  as C 
  from some_table 
 where someAlias1=someValue1 
   and someAlias2=someValue2
having C > someLimit1;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜