1

Can i use num_daysopen in the second select

SELECT
  DATEDIFF(DATE(NOW()), DATE(dateopened)) AS num_daysopen,
  (28 - DATEDIFF(DATE(NOW()), DATE(dateopened))) as days_left
FROM table

The following does not seem to work, it would be more readable than the above if it did?

SELECT
  DATEDIFF(DATE(NOW()), DATE(dateopened)) AS num_daysopen,
  (28 - num_daysopen) as days_left
FROM table

3 Answers 3

2

A column alias isn't available for use at the same level.
So add a derived table to add a level

SELECT
   num_daysopen,
   (28 - num_daysopen) as days_left
FROM
   (
    SELECT 
       DATEDIFF(DATE(NOW()), DATE(dateopened)) AS num_daysopen
    FROM 
       table
   ) T

See "Problems with Column Aliases" in the MySQL Docs

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for this, it answers the question and provides an alternative solution.
2

As stated in the docs

A select_expr can be given an alias using AS alias_name. The alias is used as the
expression's column name and can be used in GROUP BY, ORDER BY, or HAVING clauses.

The alias cannot be used in select_expr or in the WHERE clause.

Comments

0

The alias set with AS is used as the expression's column. It can't be used as a variable, but it can be used again to reference that column.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.