Почему отображаются какие-либо данные, когда я выполняю этот выбор в sql? - PullRequest
0 голосов
/ 09 января 2020

Я пытаюсь кодировать в sql следующую модель, которую я сделал: enter image description here

Код разделен на три части. Создание таблиц импорта, в которые я вставляю данные тремя CSV-файлами, создание таблиц модели и вставка данных в каждую таблицу с использованием импортированных данных. Насколько мне известно, модель правильно закодирована, но отношения могут быть плохо закодированы, потому что, когда я выполняю команду «select * from», я не получаю никаких данных. Как будто там, где информация не вставлена. Вот код, на который я ссылаюсь:

drop table if exists ImportA;
create table ImportA (

    id varchar(255),
    url varchar(255),
    name varchar(255),
    description text,
    picture_url varchar(255),
    street varchar(255),
    neighbourhood varchar(255),
    city varchar(255),
    state varchar(255),
    zipcode varchar(255),
    country_code varchar(255),
    country varchar(255),
    property_type varchar(255),
    accommodates varchar(255),
    bathrooms varchar(255),
    bedrooms varchar(255),
    beds varchar(255),
    amenities text,
    square_feet varchar(255),
    price varchar(255),
    weekly_price varchar(255),
    monthly_price varchar(255),
    security_deposit varchar(255),
    cleaning_fee varchar(255),
    minimum_nights varchar(255),
    maximum_nights varchar(255)
);

drop table if exists ImportH;
create table ImportH (

    url varchar(255),
    name varchar(255),
    description text,
    picture_url varchar(255),
    host_id  varchar(255),
    host_url varchar(255),
    host_name varchar(255),
    host_since varchar(255),
    host_about text,
    host_response_time varchar(255),
    host_response_rate varchar(255),
    host_is_superhost varchar(255),
    host_picture_url varchar(255),
    host_listings_count varchar(255),
    host_verifications varchar(255),
    host_identity_verified varchar(255)
);

drop table if exists ImportR;
create table ImportR (

    id varchar(255),
    url varchar(255),
    name varchar(255),
    description text,
    picture_url varchar(255),
    street varchar(255),
    neighbourhood varchar(255),
    city varchar(255),
    date_review varchar(255),
    reviewer_id varchar(255),
    reviewer_name varchar(255),
    comments text
);

copy ImportA from 'C:\BDD\apartments.csv' csv header delimiter ',';
copy ImportH from 'C:\BDD\hosts.csv' csv header delimiter ',';
copy ImportR from 'C:\BDD\review.csv' csv header delimiter ',';

drop table if exists Country cascade;
create table Country (

    country_code varchar(255),
    country varchar(255),
    primary key (country_code)
);

drop table if exists Payment cascade;
create table Payment (

    id_payment serial,
    price money,
    weekly_price money,
    monthly_price money,
    security_deposit money,
    cleaning_fee money,
    primary key (id_payment)
);

drop table if exists Characteristic cascade;
create table Characteristic (

    id_characteristic serial,
    property_type varchar(255),
    accommodates int,
    bathrooms int,
    bedrooms int,
    beds int,
    square_feet int,
    minimum_nights int,
    maximum_nights int,
    primary key (id_characteristic)
);

drop table if exists Host cascade;
create table Host (

    host_id serial,
    host_url varchar(255),
    host_name varchar(255),
    host_since date,
    host_about text,
    host_response_time varchar(255),
    host_response_rate varchar(255),
    host_is_superhost boolean,
    host_picture_url varchar(255),
    host_listings_count int,
    host_identity_verified boolean,
    primary key (host_id)
);

drop table if exists Media cascade;
create table Media (

    id_verification serial,
    media varchar(255),
    primary key (id_verification)
);

drop table if exists RelationHostMedia cascade;
create table RelationHostMedia (

    host_id int,
    id_verification int,
    primary key (host_id, id_verification),
    foreign key (host_id) references Host (host_id),
    foreign key (id_verification) references Media (id_verification)
);

drop table if exists Amenitie cascade;
create table Amenitie (

    id_amenitie serial,
    id_characteristic int,
    amenitie varchar(255),
    primary key (id_amenitie),
    foreign key (id_characteristic) references Characteristic (id_characteristic)
);

drop table if exists Place cascade;
create table Place (

    id_place serial,
    street varchar(255),
    neighbourhood varchar(255),
    city varchar(255),
    state varchar(255),
    zipcode varchar(255),
    country_code varchar(255),
    primary key (id_place),
    foreign key (country_code) references Country (country_code)
);

drop table if exists Apartment cascade;
create table Apartment (

    id_apartment serial,
    url varchar(255),
    name varchar(255),
    description text,
    picture_url varchar(255),
    id_place int,
    id_payment int,
    id_characteristic int,
    host_id int,
    primary key (id_apartment),
    foreign key (id_place) references Place (id_place),
    foreign key (id_payment) references Payment (id_payment),
    foreign key (id_characteristic) references Characteristic (id_characteristic),
    foreign key (host_id) references Host (host_id)
);

drop table if exists Reviewer cascade;
create table Reviewer (

    id_reviewer serial,
    reviewer_name varchar(255),
    primary key (id_reviewer)
);

drop table if exists Review cascade;
create table Review (

    id_review serial,
    id_reviewer int,
    id_apartment int,
    date_review date,
    comments text,
    primary key (id_review),
    foreign key (id_reviewer) references Reviewer (id_reviewer),
    foreign key (id_apartment) references Apartment (id_apartment)
);

insert into Country (country_code, country)
select distinct country_code, country
from ImportA;

insert into Payment (price, weekly_price, monthly_price, security_deposit, cleaning_fee)
select cast(price as money), cast(weekly_price as money), cast(monthly_price as money), cast(security_deposit as money), cast(cleaning_fee as money)
from ImportA;

insert into Characteristic (property_type, accommodates, bathrooms, bedrooms, beds, square_feet, minimum_nights, maximum_nights)
select property_type, cast(accommodates as int), cast(bathrooms as int), cast(bedrooms as int), cast(beds as int), cast(square_feet as int), cast(minimum_nights as int), cast(maximum_nights as int)
from ImportA;

insert into Host (host_id, host_url, host_name, host_since, host_about, host_response_time, host_response_rate, host_is_superhost, host_picture_url, host_listings_count, host_identity_verified)
select distinct cast(host_id as int), host_url, host_name, cast(host_since as date), cast(host_about as text), host_response_time, host_response_rate, cast(host_is_superhost as boolean), host_picture_url, cast(host_listings_count as int), cast(host_identity_verified as boolean)
from ImportH;

insert into Media (media)
select host_verifications
from ImportH;

insert into RelationHostMedia (host_id, id_verification)
select distinct host_id, id_verification
from Host, Media;

insert into Amenitie (id_characteristic, amenitie)
select id_characteristic, amenities
from Characteristic, ImportA;

insert into Place (street, neighbourhood, city, state, zipcode, country_code)
select street, neighbourhood, city, state, zipcode, country_code
from ImportA, Country;

insert into Reviewer (reviewer_name)
select reviewer_name
from ImportR;

insert into Apartment (id_apartment, url, name, description, picture_url, id_place, id_payment, id_characteristic, host_id)
select cast(id_apartment as int), url, name, cast(description as text), picture_url, id_place, id_payment, id_characteristic, host_id
from ImportA, Place, Payment, Characteristic, Host;

insert into Review (id_reviewer, id_apartment, date_review, comments)
select id_reviewer, id_apartment, cast(date_review as date), comments
from Reviewer, Apartment, ImportR;

select * from Place;

Я использую PostgreSQL на случай, если кому-то интересно.

Что не так? Заранее спасибо

1 Ответ

2 голосов
/ 09 января 2020

В зависимости от вашего сценария наличие или отсутствие данных в конце Place зависит от целого ряда других вещей, работающих правильно, таких как первая копия таблицы из файла C:\BDD\apartments.csv. Либо файлы импорта пусты, либо выдается сообщение об ошибке, которого вы не видите.

Чтобы устранить неполадки, возникающие при возникновении ошибки, я сначала подтвердил бы, что исходные таблицы root (ImportA, ImportH, ImportR ) содержат записи после запуска скрипта.

Предполагая, что у них есть записи, я предлагаю скопировать и вставить скрипт по одной инструкции за раз в ваш SQL клиент и выполнить. Продолжайте, пока не найдете первую ошибку. Исправьте это и продолжайте выполнять один оператор за раз, пока вы не докажете, что ни один оператор не приводит к ошибке.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...