Skip to content

Instantly share code, notes, and snippets.

@ziminator
Last active March 19, 2019 11:19
Show Gist options
  • Save ziminator/2158c861c5b4c37af2d12b2a43ac182b to your computer and use it in GitHub Desktop.
Save ziminator/2158c861c5b4c37af2d12b2a43ac182b to your computer and use it in GitHub Desktop.
Создайте базу данных test_guru
------------------------------
postgres=# CREATE DATABASE test_guru;
CREATE DATABASE
postgres=#
Обновите атрибуты title и level для строки из таблицы tests с помощью одного запроса
------------------------------------------------------------------------------------
postgres=# UPDATE tests
postgres-# SET title = 'HTML 5.2', level = 12
postgres-# WHERE title = 'HTML';
UPDATE 1
postgres=# SELECT * FROM tests;
id | title | level | categories_id
----+---------------+-------+---------------
2 | PHP | 20 | 2
3 | Ruby language | 88 | 3
4 | Rails | 86 | 3
5 | SQL | 84 |
1 | HTML 5.2 | 12 | 1
(5 rows)
Удалите все вопросы для конкретного теста с помощью одного запроса
------------------------------------------------------------------
postgres=# DELETE
postgres-# FROM questions
postgres-# WHERE tests_id = 5;
DELETE 1
postgres=# SELECT * FROM questions;
id | body | tests_id
----+----------------------+----------
1 | Question about HTML | 1
2 | Question about PHP | 2
3 | Question about Ruby | 3
4 | Question about Rails | 4
(4 rows)
С помощью JOIN выберите названия всех тестов и названия их категорий
--------------------------------------------------------------------
postgres=# SELECT tests.title AS test_title, categories.title AS categories_title
postgres-# FROM tests
postgres-# JOIN categories
postgres-# ON tests.categories_id = categories.id;
test_title | categories_title
---------------+-------------------
PHP | Backend
Ruby language | Movie Development
Rails | Movie Development
HTML 5.2 | Frontend
(4 rows)
С помощью JOIN выберите содержание всех вопросов (атрибут body) и названия связанных с ними тестов
--------------------------------------------------------------------------------------------------
postgres=# SELECT questions.body, tests.title
postgres-# FROM questions
postgres-# JOIN tests
postgres-# ON questions.tests_id = tests.id;
body | title
----------------------+---------------
Question about HTML | HTML 5.2
Question about PHP | PHP
Question about Ruby | Ruby language
Question about Rails | Rails
(4 rows)
Таблицу categories с атрибутом title
------------------------------------
postgres=# CREATE TABLE categories (
postgres(# id serial PRIMARY KEY,
postgres(# title varchar(50)
postgres(# );
CREATE TABLE
postgres=#
Таблицу tests в которой должны быть атрибуты title, level, внешний ключ к таблице categories
--------------------------------------------------------------------------------------------
postgres=# CREATE TABLE tests (
postgres(# id serial PRIMARY KEY,
postgres(# title varchar(50),
postgres(# level int,
postgres(# categories_id int
postgres(# );
CREATE TABLE
postgres=#
Таблицу questions в которой должен быть атрибут body и внешний ключ к таблице tests
-----------------------------------------------------------------------------------
postgres=# CREATE TABLE questions (
postgres(# id serial PRIMARY KEY,
postgres(# body varchar(25),
postgres(# tests_id int
postgres(# );
CREATE TABLE
postgres=#
Создайте 3 строки в таблице categories
--------------------------------------
postgres=# INSERT INTO categories(title) VALUES
postgres-# ('Frontend'),
postgres-# ('Backend'),
postgres-# ('Movie Development');
INSERT 0 3
postgres=# SELECT * FROM categories;
id | title
----+-------------------
1 | Frontend
2 | Backend
3 | Movie Development
(3 rows)
Создайте 5 строк в таблице tests (хотя бы 3 из них должны иметь отличное от NULL
значение в атрибуте внешнего ключа к таблице categories)
--------------------------------------------------------
postgres=# INSERT INTO tests(title, level, categories_id) VALUES
postgres-# ('HTML', 10, 1),
postgres-# ('PHP', 20, 2),
postgres-# ('Ruby language', 88, 3),
postgres-# ('Rails', 86, 3),
postgres-# ('SQL', 84, NULL);
INSERT 0 5
postgres=# SELECT * FROM tests;
id | title | level | categories_id
----+---------------+-------+---------------
1 | HTML | 10 | 1
2 | PHP | 20 | 2
3 | Ruby language | 88 | 3
4 | Rails | 86 | 3
5 | SQL | 84 |
(5 rows)
Создайте 5 строк в таблице questions
------------------------------------
postgres=# INSERT INTO questions(body, tests_id) VALUES
postgres-# ('Question about HTML', 1),
postgres-# ('Question about PHP', 2),
postgres-# ('Question about Ruby', 3),
postgres-# ('Question about Rails', 4),
postgres-# ('Question about SQL', 5);
INSERT 0 5
postgres=# SELECT * FROM questions;
id | body | tests_id
----+----------------------+----------
1 | Question about HTML | 1
2 | Question about PHP | 2
3 | Question about Ruby | 3
4 | Question about Rails | 4
5 | Question about SQL | 5
(5 rows)
Выберите все тесты с уровнем 2 и 3
----------------------------------
postgres=# SELECT * FROM tests WHERE level in (20,88);
id | title | level | categories_id
----+---------------+-------+---------------
2 | PHP | 20 | 2
3 | Ruby language | 88 | 3
(2 rows)
Выберите все вопросы для определённого теста
--------------------------------------------
postgres=# SELECT *
postgres-# FROM questions
postgres-# WHERE tests_id = 2;
id | body | tests_id
----+--------------------+----------
2 | Question about PHP | 2
(1 row)
@BubuntuClu
Copy link

https://gist.github.com/ziminator/2158c861c5b4c37af2d12b2a43ac182b#file-gistfile3-txt-L8 и https://gist.github.com/ziminator/2158c861c5b4c37af2d12b2a43ac182b#file-gistfile4-txt-L7 нужно указать что это внешние ключи

https://gist.github.com/ziminator/2158c861c5b4c37af2d12b2a43ac182b#file-gistfile12-txt-L4 - тут тоже надо выбрать только названия, но тут один момент что у тебя одинаково называются колонки. посмотри синтаксис alias

https://gist.github.com/ziminator/2158c861c5b4c37af2d12b2a43ac182b#file-gistfile8-txt-L4 - тут надо выбирать по уровню, а не по id. можно сделать так level in (2,3)

@ziminator
Copy link
Author

С алиасом всё просто и понятно, я переделал. С level in тоже вроде всё понятно, переделал.
Вопрос, как указать, что это внешние ключи? Самое простое это дописать в таблице questions у поля tests_id REFERENCES tests, тогда это будет внешний ключ. Правильно я понимаю?

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