【问题标题】:PostgreSQL: How to add Column from other table in select statement?PostgreSQL:如何在选择语句中从其他表中添加列?
【发布时间】:2016-03-22 01:32:02
【问题描述】:

我正在尝试像以前在 MSSQL 中那样从另一个表中选择一列:

 select * , Date = (select top 1 Date from [dbo].TableB where status = 1 order by Date desc)
 from [dbo].TableA

如何在 PostgreSQL 中做到这一点?

附加样本数据:

表A

Names

Richards
Marcos
Luke
Matthew
John    

表B

Date        Status
2016-01-01  1
2016-01-02  0
2016-01-03  1
2016-01-04  1
2016-01-05  1 

预期输出:

Name        Date
Richards    2016-01-02
Marcos      2016-01-02
Luke        2016-01-02
Matthew     2016-01-02
John        2016-01-02

谢谢!

【问题讨论】:

  • select * , (select NewColumn from [dbo].TableB) as NewColumn 不行吗?
  • 您能否发布示例数据和预期结果?您在tableb 中只有一条记录吗?如果不是,它将返回多个结果并很可能导致错误...
  • @sgeddes- 已经编辑了我的问题。
  • @TimBiegeleisen - 是的,它在 postgresql 中不起作用。

标签: sql postgresql


【解决方案1】:

Date = (...) 是无效的(标准)SQL,不能在 Postgres(或除 SQL Server 之外的任何其他 DBMS)中工作

在 SQL(和 Postgres)中使用AS ... 定义列别名。 Postgres 也没有top。它使用limit

在 SQL 中也不允许在标识符中使用方括号。所以[dbo]需要变成dbo或者"dbo"depending on how you created the schema

select a.*, 
       (select date
        from dbo.tableb as b
        where b.status = 1 
        order by b.date desc
        limit 1) as date
from dbo.tablea a

date 是保留字,不应用作标识符(列名)

如果你想使用标准的ANSI SQL,你也可以使用fetch first 1 row only代替limit 1

另一种选择是使用max() 代替完全不需要限制的子选择中的限制:

select a.*, 
       (select max(date)
        from dbo.tableb as b
        where b.status = 1) as date
from dbo.tablea a

【讨论】:

    【解决方案2】:

    我不确定这是否是正确的语法,但您尝试过吗:

    select * , (select NewColumn from [dbo].TableB) as NewColumn 
     from [dbo].TableA
    

    希望对你有帮助。

    【讨论】:

    • 在 postgreSQL 中不可能。 :(
    • 如果 tableb 多于一行,这将不起作用。在 SQL Server 和 Postgres 中都没有([dbo]. 无论如何都是无效的标识符)
    【解决方案3】:

    我对 PostgreSQL 不太熟悉,但 SQL 仍然是 SQL。 首先要说的是,您必须在第二个表查询中只有一个结果,您可以在

     SELECT 
            A.*
            (select NewColumn from [dbo].TableB.NewColumn) as NewColumn 
    FROM TableA
    

    但是我认为你需要声明一个连接条件。

     SELECT 
            A.*
            (select NewColumn from [dbo].TableB.NewColumn where A.Col1 = TableB.col1)
    FROM TableA A
    

    没有一个真实的例子,我不能更具体。

    【讨论】:

      【解决方案4】:

      试试这个:

      select a.*, b.column
      from tableA as a, tableB as b;
      

      【讨论】:

        【解决方案5】:

        你可以试试CROSS JOIN:

        SELECT * FROM
            (SELECT * FROM dbo.TableA),
            (SELECT Date FROM dbo.TableB WHERE status = 1 ORDER BY Date DESC LIMIT 1)
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-03-22
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多