Perform filtering on an alias in MySQL?

MySQLMySQLi Database

For this, use alias on HAVING clause.

Let us first create a table −

mysql> create table DemoTable755 (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Score1 int,
   Score2 int
);
Query OK, 0 rows affected (0.62 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable755(Score1,Score2) values(30,23);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable755(Score1,Score2) values(50,60);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable755(Score1,Score2) values(89,90);
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable755(Score1,Score2) values(99,99);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable755(Score1,Score2) values(40,43);
Query OK, 1 row affected (0.14 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable755;

This will produce the following output -

+----+--------+--------+
| Id | Score1 | Score2 |
+----+--------+--------+
|  1 |     30 |     23 |
|  2 |     50 |     60 |
|  3 |     89 |     90 |
|  4 |     99 |     99 |
|  5 |     40 |     43 |
+----+--------+--------+
5 rows in set (0.00 sec)

Following is the query to perform filtering on an alias in MySQL. Here, we are adding the score and displaying the matching result as in the query with HAVING clause. The filtered record displays the ID as well as result with scores −

mysql> select Score1+Score2 AS Result,DemoTable755.* from DemoTable755 having Result=83;

This will produce the following output -

+--------+----+--------+--------+
| Result | Id | Score1 | Score2 |
+--------+----+--------+--------+
|     83 |  5 |     40 |     43 |
+--------+----+--------+--------+
1 row in set (0.00 sec)
raja
Published on 03-Sep-2019 07:57:07
Advertisements