在条件

时间:2017-02-26 16:35:58

标签: sql postgresql

考虑以下关系。

enter image description here

如果在基于复合主键Tenants的{​​{1}}中找不到NewRentPayments的元组,我试图在Tenants的{​​{1}}中添加新行NewRentPayments

查看我的查询,您将有更好的想法

houseid

apartmentnumber上的错误。

insert into Tenants(houseid, apartmentnumber, leasetenantssn, leasestartdate, leaseexpirationdate, rent, lastrentpaiddate, rentoverdue)
(
    select n.* from NewRentPayments as n left join Tenants as t 
    on 
    t.houseid = n.houseid 
    and 
    t.apartmentnumber = n.apartmentnumber
    where
    t.houseid is null
    or
    t.apartmentnumber is null
) as newval
(newval.houseid, newval.apartmentnumber, newval.leasetenantssn, now(), NULL, newval.rent, newval.datepaid, 'f');

注意:这不是来自另一个表的一个表中的简单插入值,而是here。在我的情况下,我在插入as newval元组时,也会在ERROR: syntax error at or near "as" LINE 12: ) as newval ^ ********** Error ********** ERROR: syntax error at or near "as" SQL state: 42601 Character: 345 行中插入一些常量/自定义值。

我正在使用Postgresql。

1 个答案:

答案 0 :(得分:1)

您需要将值插入到选择中。

试试这个:

insert into Tenants (houseid, apartmentnumber, leasetenantssn, leasestartdate, leaseexpirationdate, rent, lastrentpaiddate, rentoverdue)
select newval.houseid, newval.apartmentnumber, newval.leasetenantssn, now(), null, newval.rent, newval.datepaid, 'f'
from (
    select n.*
    from NewRentPayments as n
    left join Tenants as t on t.houseid = n.houseid
        and t.apartmentnumber = n.apartmentnumber
    where t.houseid is null
        or t.apartmentnumber is null
    ) as newval;