How to create a virtual column using MySQL SELECT?

If I do SELECT a AS b and b is not a column in the table, will the query create a “virtual” column?

in fact, I need to include some virtual column in the query and process some information in the query so that I can use it with each element later.

+61
php mysql select
Jan 18 '09 at 14:57
source share
5 answers

something like

SELECT id, email, IF(actived = 1, 'enabled', 'disabled') AS account_status FROM users 

this allows you to do operations and display them as columns.

EDIT:

you can also use joins and show operators as columns:

  SELECT u.id, e.email, IF(c.id IS NULL, 'no selected', c.name) as country FROM users u LEFT JOIN countries c ON u.country_id = c.id 
+81
Jan 18 '09 at 15:01
source share

Try this if you want to create a virtual column "age" in the select statement:

 select brand, name, "10" as age from cars... 
+58
Jul 09 2018-11-11T00: 00Z
source share

You can add virtual columns as

 SELECT '1' as temp 

But if you try to set a condition in which an additional column will be added, it will not work and will display an error message because the column does not exist.

We can solve this problem by returning the sql result as table.ie,

 SELECT tb.* from (SELECT 1 as temp) as tb WHERE tb.temp = 1 
+10
Jan 01 '15 at 6:11
source share

SELECT only retrieves data from the database, it does not change the table itself.

If you write

 SELECT a AS b FROM x 

"b" is just an alias in the request. It does not create an additional column. Your result in the example will contain only one column named "b". But the column in the table will remain "a". "b" is just another name.

I really don't understand what you mean, "so I can use it with every item later." You mean later in the select statement or later in your application. Perhaps you can provide sample code.

+3
Jan 18 '09 at 15:07
source share

Your syntax would create an alias for a as b, but it would not have a frame outside the results of the statement. It looks like you can create a VIEW

0
Jan 18 '09 at 15:08
source share



All Articles