Skip to content

Instantly share code, notes, and snippets.

@SergeGray
Created August 24, 2019 20:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SergeGray/ca10a78a7df424af03c68b8b472f569c to your computer and use it in GitHub Desktop.
Save SergeGray/ca10a78a7df424af03c68b8b472f569c to your computer and use it in GitHub Desktop.
postgres=# CREATE DATABASE test_guru;
CREATE DATABASE
postgres=# CREATE TABLE categories (
postgres(# id serial PRIMARY KEY,
postgres(# title varchar(50)
postgres(# );
CREATE TABLE
postgres=# CREATE TABLE tests (
postgres(# id serial PRIMARY KEY,
postgres(# title varchar(50),
postgres(# level int,
postgres(# category_id int
postgres(# );
CREATE TABLE
postgres=# CREATE TABLE questions (
postgres(# body text,
postgres(# test_id int
postgres(# );
CREATE TABLE
postgres=# INSERT INTO categories(title) VALUES
postgres-# ('Web Development'),
postgres-# ('General'),
postgres-# ('Machine Learning');
INSERT 0 3
postgres=# SELECT * FROM categories;
id | title
----+------------------
1 | Web Development
2 | General
3 | Machine Learning
(3 rows)
postgres=# INSERT INTO tests(title, level, category_id) VALUES
postgres-# ('Ruby', 0, 2),
postgres-# ('Rails', 1, 1),
postgres-# ('JavaScript', 2, 1),
postgres-# ('Artificial Intelligence', 3, 3),
postgres-# ('Python', 0, 2);
INSERT 0 5
postgres=# SELECT * FROM tests;
id | title | level | category_id
----+-------------------------+-------+-------------
1 | Ruby | 0 | 2
2 | Rails | 1 | 1
3 | JavaScript | 2 | 1
4 | Artificial Intelligence | 3 | 3
5 | Python | 0 | 2
(5 rows)
postgres=# INSERT INTO questions(body, test_id) VALUES
postgres-# ('Input method in ruby', 1),
postgres-# ('Default file extension for views', 2),
postgres-# ('Value to represent absence of value', 3),
postgres-# ('Acronym for Artificial Intelligence', 4),
postgres-# ('Name of a data type that stores key-value pairs', 5);
INSERT 0 5
postgres=# SELECT * FROM tests WHERE (level = 2) OR (level = 3);
id | title | level | category_id
----+-------------------------+-------+-------------
3 | JavaScript | 2 | 1
4 | Artificial Intelligence | 3 | 3
(2 rows)
postgres=# SELECT * FROM questions WHERE (test_id = 2);
body | test_id
----------------------------------+---------
Default file extension for views | 2
(1 row)
postgres=# UPDATE tests SET title = 'Ruby on Rails', level = 2 WHERE (title = 'Rails');
UPDATE 1
postgres=# DELETE FROM questions WHERE (test_id = 4);
DELETE 1
postgres=# SELECT tests.title, categories.title FROM tests JOIN categories ON
tests.category_id = categories.id;
title | title
-------------------------+------------------
Ruby | General
JavaScript | Web Development
Artificial Intelligence | Machine Learning
Python | General
Ruby on Rails | Web Development
(5 rows)
postgres=# SELECT questions.body, tests.title FROM questions JOIN tests ON
postgres-# questions.test_id = tests.id;
body | title
-------------------------------------------------+---------------
Input method in ruby | Ruby
Default file extension for views | Ruby on Rails
Value to represent absence of value | JavaScript
Name of a data type that stores key-value pairs | Python
(4 rows)
@max-underthesun
Copy link

ТЗ: "tests в которой должны быть ... внешний ключ к таблице categories"
у тебя создается просто числовое поле, а не внешний ключ
нужны не просто поля, а внешние ключи
база данных в этом случае применяет к этому полю FOREIGN KEY constraint для контроля целостности данных (Data integrity)
рекомендуется всегда обозначать для полей-связей, что это ссылка на внешний ключ

@max-underthesun
Copy link

при создании таблицы вопросов забыл создать первичный ключ и замечание по внешнему ключу такое же как для таблицы тестов

@max-underthesun
Copy link

предпоследний запрос (с "джойном")
запрос вернет две колонки title, пользоваться результатом такого запроса может оказаться затруднительно (может возникнуть путаница) - нужно как-то различать эти колонки, они же принадлежат к разным таблицам
(открой для себя SQL алиасы)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment