Skip to content

Instantly share code, notes, and snippets.

@Pekhov
Last active October 26, 2018 18:09
Show Gist options
  • Select an option

  • Save Pekhov/a8dc4f55622fedb818d047b3d59aca4f to your computer and use it in GitHub Desktop.

Select an option

Save Pekhov/a8dc4f55622fedb818d047b3d59aca4f to your computer and use it in GitHub Desktop.
sqlite3 test_guru.db
sqlite> CREATE TABLE categories(
...> id INTEGER PRIMARY KEY AUTOINCREMENT,
...> title TEXT
...> );
sqlite> CREATE TABLE tests(
...> id INTEGER PRIMARY KEY AUTOINCREMENT,
...> title TEXT,
...> level INTEGER,
...> category_id INTEGER,
...> FOREIGN KEY(category_id) REFERENCES categories(id)
...> );
sqlite> CREATE TABLE questions(
...> body TEST,
...> test_id INTEGER,
...> FOREIGN KEY(test_id) REFERENCES tests(id)
...> );
sqlite> INSERT INTO categories(title) VALUES ('world');
sqlite> INSERT INTO categories(title) VALUES ('cars');
sqlite> INSERT INTO categories(title) VALUES ('cats');
sqlite> INSERT INTO tests(title, level, category_id) VALUES ('test1', 0, 2);
sqlite> INSERT INTO tests(title, level, category_id) VALUES ('test2', 1, 2);
sqlite> INSERT INTO tests(title, level, category_id) VALUES ('test3', 2, 2);
sqlite> INSERT INTO tests(title, level, category_id) VALUES ('test1', 0, 1);
sqlite> INSERT INTO tests(title, level, category_id) VALUES ('test1', 0, 3);
sqlite> INSERT INTO questions(body, test_id) VALUES ('question1', 1);
sqlite> INSERT INTO questions(body, test_id) VALUES ('question2', 1);
sqlite> INSERT INTO questions(body, test_id) VALUES ('question1', 2);
sqlite> INSERT INTO questions(body, test_id) VALUES ('question2', 2);
sqlite> INSERT INTO questions(body, test_id) VALUES ('question3', 2);
sqlite> SELECT *
...> FROM tests
...> WHERE level = 2 OR level = 3;
id title level category_id
---------- ---------- ---------- -----------
3 test3 2 2
sqlite> SELECT *
...> FROM questions
...> WHERE test_id = 2;
body test_id
---------- ----------
question1 2
question2 2
question3 2
sqlite> update tests set title = 'modify_title', level = 3 where id = 4;
sqlite> DELETE
...> FROM questions
...> WHERE test_id = 2;
sqlite> SELECT tests.title, categories.title
...> FROM tests
...> JOIN categories
...> ON tests.category_id = categories.id;
title title
---------- ----------
test1 cars
test2 cars
test3 cars
modify_tit world
test1 cats
sqlite> SELECT questions.body, tests.title
...> FROM questions
...> JOIN tests
...> ON questions.test_id = tests.id;
body title
---------- ----------
question1 test1
question2 test1
@BubuntuClu
Copy link

здесь стоит сделать alias на выборку столбцов, они у тебя с одним именем и не понятно где какой

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