繁体   English   中英

PostgreSQL:如何在 select 语句中添加来自其他表的列?

[英]PostgreSQL: How to add Column from other table in select statement?

我正在尝试从另一个表中选择一列,就像我以前在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 
 from [dbo].TableA

我希望它有帮助。

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

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

SQL 中也不允许在标识符中使用方括号。 所以[dbo]需要变成dbo"dbo" 这取决于你如何创建 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

尝试这个:

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

我对 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

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

你可以尝试做一个CROSS JOIN

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM