dfg*_*dfg 4 postgresql postgresql-9.3
insert into addresses(street, city, user_id)
select
'street1','LA', 2
where exists (select * from users where users.id = $$$$$ AND users.storeaddress='true'))
Run Code Online (Sandbox Code Playgroud)
仅当用户的 storeaddress 值为“true”时,我才想插入用户的地址。
我希望 sql 自动使用 2 代替 $$$$$。如何在sql中做到这一点?
如果我简单地用 user_id 代替 $$$$$ 我得到
HINT: There is a column named "user_id" in table "addresses", but it cannot be referenced from this part of the query.
Run Code Online (Sandbox Code Playgroud)
小智 5
您可以使用 CTE 来提供值:
with data (street, city, user_id) as (
values ('street1','LA', 2)
)
insert into addresses(street, city, user_id)
select *
from data
where exists (select *
from users
where users.id = data.user_id
and users.storeaddress = true);
Run Code Online (Sandbox Code Playgroud)
或者派生表:
insert into addresses(street, city, user_id)
select *
from (
values ('street1','LA', 2)
) as data (street, city, user_id)
where exists (select *
from users
where users.id = data.user_id
and users.storeaddress = true);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5869 次 |
最近记录: |