Advertisement
Guest User

Untitled

a guest
Dec 12th, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. -- 1 --
  2. create table list (
  3. LastName varchar(255),
  4. FirstName varchar(255),
  5. Grade int,
  6. Classroom int
  7. );
  8. copy list
  9. from '/home/alex/Загрузки/list.csv' WITH CSV HEADER DELIMITER ',';
  10.  
  11. alter table list
  12. add column id bigserial Primary KEY;
  13.  
  14. create table teachers (
  15. LastName varchar(255),
  16. FirstName varchar(255),
  17. Classroom int
  18. );
  19.  
  20. copy teachers
  21. from '/home/alex/Загрузки/teachers.csv' WITH CSV HEADER DELIMITER ',';
  22.  
  23. alter table teachers
  24. add column id bigserial Primary KEY;
  25.  
  26. -- 2 --
  27. select teachers.FirstName firstname, teachers.LastName lastname, count(teachers.Classroom) quantity
  28. from teachers
  29. inner join list on list.Classroom = teachers.Classroom
  30. group by teachers.firstname, teachers.lastname;
  31.  
  32. -- 3 --
  33. explain
  34. select teachers.FirstName firstname, teachers.LastName lastname, count(teachers.Classroom) classroom
  35. from teachers
  36. inner join list on list.Classroom = teachers.Classroom
  37. group by teachers.firstname, teachers.lastname;
  38.  
  39. -- 4 --
  40. -- Нормализация
  41. select LastName, FirstName, id
  42. into student_name
  43. from list;
  44.  
  45. alter table student_name
  46. add Primary KEY(id);
  47.  
  48.  
  49. select Grade, id
  50. into student_grade
  51. from list;
  52.  
  53. alter table student_grade
  54. add Primary KEY(id);
  55.  
  56.  
  57. select Classroom, id
  58. into student_classroom
  59. from list;
  60.  
  61. alter table student_classroom
  62. add Primary KEY(id);
  63.  
  64.  
  65. select teachers.FirstName t_firstname, teachers.LastName t_lastname, list.id s_id
  66. into teacher_student
  67. from teachers
  68. inner join list on list.Classroom = teachers.Classroom;
  69.  
  70. alter table teacher_student
  71. add Primary KEY(s_id);
  72.  
  73. -- проверим запрос
  74. explain
  75. select distinct t_lastname, t_firstname, count(*)
  76. from teacher_student
  77. group by t_lastname, t_firstname;
  78.  
  79. -- первый cost стал ниже
  80.  
  81. -- 5 --
  82. explain
  83. select LastName, FirstName
  84. from student_name
  85. inner join student_grade on student_name.id = student_grade.id
  86. where Grade > 3;
  87.  
  88. -- 6 --
  89. CREATE INDEX btree ON student_grade(id);
  90. drop index btree;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement