SQL Use alias in Where statement

前端 未结 10 1223
南笙
南笙 2020-11-29 06:09

I wounder how I could use an alias in a where statement.

Example :

SELECT SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3)  AS Col1
FROM MyTable
W         


        
相关标签:
10条回答
  • 2020-11-29 06:45

    use a view or a derived table.

    Using a derived table, your example would look like:

    select col1 
    from 
    (SELECT SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3)  AS Col1
    FROM MyTable) 
    where col1='Mysearch'
    
    0 讨论(0)
  • 2020-11-29 06:48

    Use a subquery:

    SELECT * 
    FROM 
      (SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3) AS Col1 FROM MyTable)
    WHERE Col1 = 'MySearch'
    
    0 讨论(0)
  • 2020-11-29 06:48

    The answer is you can't - you can do this

    SELECT 
        SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3)  AS Col1
    FROM 
        MyTable
    WHERE 
        SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3) = 'MySearch'
    
    0 讨论(0)
  • 2020-11-29 06:52

    You can do this:

    SELECT Col1
    FROM ( SELECT SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3) AS Col1 ) AS x
    WHERE Col1 = 'MySearch'
    
    0 讨论(0)
  • 2020-11-29 06:52

    With PostgreSQL 9.3+ OR Oracle 12c, there is now lateral join that allows creating an alias.

    Lateral joins are joints inside witch you can reference preceding tables.

    SELECT col1, col2,col3
    FROM MyTable m
    JOIN LATERAL (
        SELECT SUBSTRING(m.Column1, 1, 4) + SUBSTRING(Column1, 4, 3)  AS Col1 
    ) x ON true
    WHERE Col1 = 'MySearch'
    

    With this syntax, you don't have to use '*' that can be non-performing or recopy all the columns.

    0 讨论(0)
  • 2020-11-29 06:53

    Not possible, but you can do the following:

    SELECT SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3)  AS Col1
    FROM MyTable
    WHERE SUBSTRING(Column1, 1, 4) + SUBSTRING(Column1, 4, 3) = 'MySearch'
    

    No subqueries or hacks required

    0 讨论(0)
提交回复
热议问题