For some reason, this doesn't work:
select substring(rating, instr(rating,',') +1, +2) as val from users where val = '15';
It gives this error:
ERROR 1054 (42S22): Unknown column 'val' in 'where clause'
How do I do it then?
You should use the WHERE clause to filter the records and fetching only the necessary records. The WHERE clause is not only used in the SELECT statement, but it is also used in the UPDATE, DELETE statement, etc., which we would examine in the subsequent chapters.
The WHERE clause is used to filter records. It is used to extract only those records that fulfill a specified condition.
WHERE clause Syntax. The basic syntax for the WHERE clause when used in a MySQL SELECT WHERE statement is as follows. “WHERE” is the keyword that restricts our select query result set and “condition” is the filter to be applied on the results. The filter could be a range, single value or sub query.
The SELECT statement is used to select data from a database. The data returned is stored in a result table, called the result-set.
First, you cannot use ALIAS
on the WHERE
clause. You shoul be using the column,
SELECT SUBSTRING(rating, INSTR(rating,',') +1, +2) AS val FROM users WHERE SUBSTRING(rating, INSTR(rating,',') +1, +2) = '15'
The reason is as follows: the order of operation is SQL,
the ALIAS
takes place on the SELECT
clause which is before the WHERE
clause.
if you really want to use the alias, wrap it in a subquery,
SELECT * FROM ( SELECT SUBSTRING(rating, INSTR(rating,',') +1, +2) AS val FROM users ) s WHERE val = '15'
You sure can with MySQL, please see below, just tested this and it works fine:
Select substring(rating, instr(rating,',') +1, +2) as val From users Having val = '15';
You can also do things like "having val is null" etc.
With ALIASes you can't use WHERE, but using HAVING does the trick.
H
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With