Last active
December 15, 2019 09:56
-
-
Save shilovk/ecef8f144e9b255612d2d7061f08727b to your computer and use it in GitHub Desktop.
Задание по основам баз данных и SQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
homework 3.7 | |
gist.github.com | |
1. | |
CREATE DATABASE test_guru; | |
\c test_guru | |
CREATE TABLE categories ( | |
id serial PRIMARY KEY, | |
title varchar(25) NOT NULL | |
); | |
CREATE TABLE tests ( | |
id serial PRIMARY KEY, | |
title varchar(50), | |
level int NOT NULL, | |
category_id int NOT NULL, | |
FOREIGN KEY (category_id) REFERENCES categories(id) | |
); | |
CREATE TABLE questions ( | |
id serial PRIMARY KEY, | |
body varchar(250) NOT NULL, | |
test_id int NOT NULL, | |
FOREIGN KEY (test_id) REFERENCES tests(id) | |
); | |
2. | |
INSERT INTO categories(title) VALUES | |
('Frontend'), | |
('Backend'), | |
('Machine Learning'); | |
INSERT INTO tests(title, level, category_id) VALUES | |
('HTML', 1, 1), | |
('Go', 2, 2), | |
('Ruby', 3, 2), | |
('React', 4, 3), | |
('Rails', 5, 2); | |
INSERT INTO questions(body, test_id) VALUES | |
('header', 1), | |
('class', 3), | |
('array', 3), | |
('migrate', 5), | |
('rake', 5); | |
SELECT * | |
FROM tests | |
WHERE level IN (2, 3); | |
SELECT * | |
FROM questions | |
WHERE test_id = 5; | |
UPDATE tests | |
SET title = 'Ruby Language', | |
level = 4 | |
WHERE title = 'Ruby'; | |
DELETE FROM questions | |
WHERE test_id = 5; | |
SELECT | |
tests.title AS test_title, | |
categories.title AS category_title | |
FROM tests | |
JOIN categories | |
ON tests.category_id = categories.id; | |
SELECT questions.body, tests.title | |
FROM questions | |
JOIN tests | |
ON questions.test_id = tests.id; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
предпоследний запрос вернет две колонки
title
, пользоваться результатом такого запроса может оказаться затруднительно (может возникнуть путаница)нужно как-то различать эти колонки, они же принадлежат к разным таблицам
открой для себя SQL алиасы