在 SQL 中选择一个带有虚拟值的虚拟列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1094996/
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
Select a dummy column with a dummy value in SQL?
提问by kal
I have a table with the following
我有一张表,内容如下
Table1
col1 col2
------------
1 A
2 B
3 C
0 D
Result
结果
col1 col2 col3
------------------
0 D ABC
I am not sure how to go about writing the query , col1 and col2 can be selected by this
我不确定如何编写查询,可以通过此选择 col1 和 col2
select col1, col2 from Table1 where col1 = 0;
How should I go about adding a col3 with value ABC.
我应该如何添加一个值为 ABC 的 col3。
回答by Andrew Hare
Try this:
尝试这个:
select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;
回答by Alex N.
If you meant just ABC as simple value, answer above is the one that works fine.
如果您的意思只是 ABC 作为简单值,那么上面的答案是有效的。
If you meant concatenation of values of rows that are not selected by your main query, you will need to use a subquery.
如果您的意思是连接主查询未选择的行的值,则需要使用子查询。
Something like this may work:
像这样的事情可能会奏效:
SELECT t1.col1,
t1.col2,
(SELECT GROUP_CONCAT(col2 SEPARATOR '') FROM Table1 t2 WHERE t2.col1 != 0) as col3
FROM Table1 t1
WHERE t1.col1 = 0;
Actual syntax maybe a bit off though
虽然实际语法可能有点偏离