php 如何使用 MySQL SELECT 创建虚拟列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/455261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create virtual column using MySQL SELECT?
提问by Skuta
If I do SELECT a AS b and b is not a column in the table, would query create the "virtual" column?
如果我做 SELECT a AS b 并且 b 不是表中的列,查询会创建“虚拟”列吗?
in fact, I need to incorporate some virtual column into the query and process some information into the query so I can use it with each item later on.
事实上,我需要将一些虚拟列合并到查询中,并将一些信息处理到查询中,以便我以后可以将它用于每个项目。
回答by Gabriel Sosa
Something like:
就像是:
SELECT id, email, IF(active = 1, 'enabled', 'disabled') AS account_status FROM users
This allows you to make operations and show it as columns.
这允许您进行操作并将其显示为列。
EDIT:
编辑:
you can also use joins and show operations 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
回答by ninsky
Try this one if you want to create a virtual column "age" within a select statement:
如果你想在 select 语句中创建一个虚拟列“age”,试试这个:
select brand, name, "10" as age from cars...
回答by rb vishnu
You can add virtual columns as
您可以将虚拟列添加为
SELECT '1' as temp
But if you tries to put where condition to additionally generated column, it wont work and will show an error message as the column doesn't exist.
但是,如果您尝试将 where 条件添加到额外生成的列中,它将不起作用,并且会显示错误消息,因为该列不存在。
We can solve this issue by returning sql result as a table.ie,
我们可以通过将 sql 结果作为 table.ie 返回来解决这个问题,
SELECT tb.* from (SELECT 1 as temp) as tb WHERE tb.temp = 1
回答by Sebastian Dietz
SELECT only retrieves data from the database, it does not change the table itself.
SELECT 仅从数据库中检索数据,它不会更改表本身。
If you write
如果你写
SELECT a AS b FROM x
"b" is just an alias name in the query. It does not create an extra column. Your result in the example would only contain one column named "b". But the column in the table would stay "a". "b" is just another name.
“b”只是查询中的别名。它不会创建额外的列。您在示例中的结果将仅包含名为“b”的一列。但是表中的列将保留为“a”。“b”只是另一个名字。
I don't really understand what you mean with "so I can use it with each item later on". Do you mean later in the select statement or later in your application. Perhaps you could provide some example code.
我真的不明白你的意思是“所以我以后可以用它来处理每个项目”。你的意思是在 select 语句后面还是在你的应用程序后面。也许您可以提供一些示例代码。

