Last active
December 8, 2019 15:49
-
-
Save vesh95/d131a5f3c4868f73699d0268b3a5ca10 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
INSERT INTO categories (title) VALUES | |
('Frontend'), | |
('Backend'), | |
('Other'); | |
INSERT INTO tests(title, level, categories_id) VALUES | |
('HTML', 1, 1), | |
('Rails', 2, 2), | |
('Django', 2, 2), | |
('MySQL', 3, NULL), | |
('JAVA', 3, NULL); | |
INSERT INTO questions(body, tests_id) VALUES | |
('element p', 1), | |
('redirect_to', 2), | |
('url_to', 3), | |
('select', 4), | |
('java?', 5); | |
/* | |
* SELECT * FROM tests WHERE level = 2 or level = 3; | |
* id | title | level | categories_id | |
* ----+--------+-------+--------------- | |
* 2 | Rails | 2 | 2 | |
* 3 | Django | 2 | 2 | |
* 4 | MySQL | 3 | | |
* 5 | JAVA | 3 | | |
*/ | |
SELECT * FROM questions WHERE tests_id = 1; | |
/* | |
* id | body | tests_id | |
* ----+-----------+---------- | |
* 1 | element p | 1 | |
*/ | |
UPDATE tests SET title = 'Java', level = 5 | |
WHERE title = 'JAVA'; | |
DELETE FROM questions | |
WHERE tests_id IN (SELECT id FROM tests WHERE title = 'HTML'); |
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
CREATE DATABASE test_guru; | |
CREATE TABLE categories ( | |
id SERIAL PRIMARY KEY, | |
title VARCHAR(255) | |
); | |
CREATE TABLE tests ( | |
id SERIAL PRIMARY KEY, | |
title VARCHAR, | |
level INT, | |
categories_id INT, | |
FOREIGN KEY (categories_id) REFERENCES categories (id) | |
); | |
CREATE TABLE questions ( | |
id SERIAL PRIMARY KEY, | |
body text, | |
tests_id INT, | |
FOREIGN KEY (tests_id) REFERENCES tests (id) | |
); | |
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
SELECT tests.title AS TestName, categories.title AS CategoryName | |
FROM tests JOIN categories | |
ON tests.categories_id = categories.id; | |
SELECT tests.title, questions.body | |
FROM questions JOIN tests | |
ON tests.id = questions.tests_id; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
файл с "джойнами"
первый запрос вернет две колонки
title
, пользоваться результатом такого запроса может оказаться затруднительно (может возникнуть путаница)нужно как-то различать эти колонки, они же принадлежат к разным таблицам
открой для себя SQL алиасы