我需要创建一个数据库,规范从 csv 文件导入的一些数据。导入表(从现在起表ImportA
)包含模型中的所有数据,例如:apartment_url
, apartment_name
, monthly_price
, weekly_price
, street
, country
等
在这个模型中,根据导入的数据,我要创建的表是:表Apartment
(将存储 apartment_url
和 apartment_name
),表 Price
(将存储 monthly_price
和 weekly_price
以及表 Place
( street
、 country
)。
提到的 3 个表是这样创建的:
表价
create table Price (
id serial,
monthly money,
weekly money,
primary key (id)
);
餐 table 位置
create table Place (
id serial,
street varchar(255),
country varchar(255),
primary key(id)
);
table 公寓
create table Apartment (
id serial,
url varchar(255),
name varchar(255),
id_price int references Price (id),
id_place int references Place (id),
primary key(id)
);
表格示例ImportA
数据:
apartment_url apartment_name monthly_price weekly_price street country
-----------------------------------------------------------------------------------------
url1 name1 10 5 a b
url2 name2 10 5 c d
url3 name3 10 5 a b
url4 name4 7 3 x y
为了将其规范化到不同的表中,我将数据正确插入到表Place
中和表Price
像这样:
insert into Place (street, country)
select distinct street, country
from ImportA;
insert into Price (monthly, weekly)
select distinct monthly_price, weekly_price
from ImportA;
所以...
select * from Place
:
id street country
--------------------------
1 a b
2 c d
3 x y
select * from Price
:
id monthly weekly
--------------------------
1 10 5
2 7 3
问题是为了填充表Apartment
我不知道如何联系id_price
和id_place
根据之前创建的表的字段。
以 ImportA
为例数据和前面的表,如果我执行 select * from Apartment
我想要的输出会是这样的:
url name id_price id_place
---------------------------------------------------
url1 name1 1 1
url2 name2 1 2
url3 name3 1 1
url4 name4 2 3
那么...我怎样才能将数据插入表Apartment
正确使用表格ImportA
, Place
和Price
?
最佳答案
只需使用加入
:
select i.url, i.name, p.id, pl.id
from importA i left join
price p
on i.monthly = p.monthly and i.weekly = p.weekly left join
place pl
on i.street = p.street and i.country = p.country;
然后您可以将其插入到您的apartment
表中。
也就是说,将价格拆分到单独的表中似乎很奇怪。我认为这些是公寓的可衡量属性。但你可能有一些理由将他们分开。此外,这些国家/地区可能也应该位于单独的表中。
关于sql - 如何将导入表中的信息分发到模型表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61424420/