【问题标题】:How to add a custom column with a default value in an sql query?如何在 sql 查询中添加具有默认值的自定义列?
【发布时间】:2014-10-23 22:22:39
【问题描述】:

所以我在 SQL (postgres) 中做一个基本的连接查询...

SELECT first_name, last_name 
FROM table1, table2 
WHERE table1.id = table2.customer_id

在返回的结果查询中,是否可以在返回的每一行中生成一个名为“default_value”的额外列,其中的字符串值为“test”,如果可以,如何?我不想用新数据永久更改表,只是在结果集中添加一个额外的列。用例是将 sql 查询存储在 Heroku 数据剪辑中,以便生成 csv 报告。

【问题讨论】:

  • 有人知道为什么这篇文章被否决了吗?

标签: sql postgresql


【解决方案1】:

是的,这很容易:

select first_name, 
       last_name,
       'test' as default_value, --<< a "virtual" column containing a character value
       42 as the_answer         --<< another column containing a numeric value
from table1 
  join table2 on table1.id = table2.customer_id;

您还应该停止在WHERE 子句中使用那些过时的隐式连接。请改用显式 JOIN 运算符。它使查询对意外忘记的连接条件更加健壮。

【讨论】:

  • 是否有任何选项可以对虚拟列的值设置条件,但 bdw 很有帮助
【解决方案2】:

“是否有任何选项可以对虚拟列的值设置条件?”

select first_name, 
   last_name,
   CASE WHEN first_name = 'Mary' THEN 'test' WHEN first_name = 'John' THEN 'test2' 
        ELSE 'Not known' END as default_value,
   42 as the_answer
from table1 
join table2 on table1.id = table2.customer_id;

【讨论】:

    猜你喜欢
    • 2019-01-03
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2010-09-08
    • 2022-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多