Uploaded by www.agranom92

БазыДанных

advertisement
Основы
тестирования
ПО
Базы данных и
коммуникация с
ними
База данных – это..
A relational database is a collection of relations or two-dimensional tables.
Database
Table name: EMP
EMPNO
7839
ENAME
KING
JOB
PRESIDENT
DEPTNO
10
7698
7782
BLAKE
CLARK
MANAGER
MANAGER
30
10
7566
JONES
MANAGER
20
Table name: DEPT
DEPTNO
10
DNAME
ACCOUNTING
LOC
NEW YORK
20
30
RESEARCH
SALES
DALLAS
CHICAGO
40
OPERATIONS
BOSTON
Система управления реляционной БД (RDBMS)
Server
User tables
Data
dictionary
Модель взаимоотношений сущностей
Отношения между таблицами реализованы:
• Each row of data in a table is uniquely identified by a
primary key (PK).
• You can logically relate data from multiple tables using
foreign keys (FK).
Table name: EMP
Table name: DEPT
EMPNO
7839
7698
ENAME
KING
BLAKE
JOB
PRESIDENT
MANAGER
DEPTNO
10
30
7782
7566
CLARK
JONES
MANAGER
MANAGER
10
20
Primary key
Foreign key
DEPTNO
10
20
DNAME
ACCOUNTING
RESEARCH
LOC
NEW YORK
DALLAS
30
40
SALES
OPERATIONS
CHICAGO
BOSTON
Primary key
Нормализация баз данных
Это процесс организации данных в таблицах
реляционной базы данных, который позволяет
минимизировать избыточность данных.
Database normalization - 1NF
The first normal form (1NF or Minimal Form) :
A relational database table that adheres to 1NF is one
that meets a certain minimum set of criteria: each
column must contain only a single value, each row
must contain the same columns, there is no sorting,
there is no duplicates.
…Ivanov, 15 department, chief…
Last Name
Position
Department №
Ivanov
Chief
15
Database normalization - 2NF
The second normal form (2NF):
is a 1NF table + if all its non-prime attributes are fully functionally
dependent on the candidate key. (A non-prime attribute is one
that does not belong to any candidate key.)
Salary depends on complex key (dep + position)
PC depends only on
position
Department №
Position
Salary
PC required
15
Chief
10k
yes
15
Engineer
3k
yes
10
Chief
8k
yes
10
Cleaner
1k
no
Database normalization - 2NF
Department №
Position
Salary
Position
PC required
15
Chief
10k
Engineer
yes
15
Engineer
3k
Chief
yes
Cleaner
no
10
Chief
8k
10
Cleaner
1k
Database normalization - 3NF
The third normal form (3NF) :
The relation (table) is in second normal form (2NF). Every nonprime attribute is non-transitively dependent (i.e. directly
dependent) on every candidate key in the table.
Phone #
transitively depends on employee, but
directly depends only on department
Employee №
Name
Department
Phone №
1
Ivanov
Functional Department
222-22-22
2
Black
Functional Department
222-22-22
3
Smith
Sales Department
333-33-33
This table in 2nd normal form as all non-prime
attributes fully depends on KEY, but not in 3rd ,
because Phone attribute depends not directly.
Database normalization - 3NF
Employee №
Last Name
Department
1
Ivanov
Functional Department
2
Petrov
Functional Department
3
Ivanov
Sales Department
Department №
Phone №
Sales Department
222-22-22
Functional Department 333-33-33
Денормализация
• Улучшение производительности сложных
запросов, которые выполняются долго за счет
добавления необходимой избыточности данных
• Упрощение выполнения запросов на клиенте (вплоть
до 1-й таблицы)
• Улучшение эффективности работы клиента с
базой
• Делает структуру проще для конечного пользователя
Relation database
•Доступ и изменение данных
в реляционной базе данных
осуществляется при помощи
выполнения команд на
структурированном языке
запросов (SQL)
Communicating with a RDBMS using SQL
SQL statement is
entered
SQL> SELECT loc
2 FROM
dept;
Statement is sent to
DB
DB
Data is displayed
LOC
------------NEW YORK
DALLAS
CHICAGO
BOSTON
Structure
Statements
Statement
Description
Data Manipulation
SELECT
Retrieves data from the database
INSERT
Adds new rows of data to the database
DELETE
Removes rows of data from the database
UPDATE
Modifies existing database data
Data Definition
CREATE TABLE
Adds a new table to the database
DROP TABLE
Removes a table from the database
ALTER TABLE
Changes the structure of an existing table
CREATE VIEW
Adds a new view to the database
DROP VIEW
Removes a view from the database
CREATE INDEX
Builds an index for a column
DROP INDEX
Removes the index for a column
CREATE SCHEMA
Adds a new schema to the database
DROP SCHEMA
Removes a schema from the database
CREATE DOMAIN
Adds a new data value domain
ALTER DOMAIN
Changes a domain definition
DROP DOMAIN
Removes a domain from the database
Statements
Access Control
GRANT
Grants user access privileges
REVOKE
Removes user access privileges
Transaction Control
COMMIT
Ends the current transaction
ROLLBACK
Aborts the current transaction
SET TRANSACTION
Defines data access characteristics of the current transaction
Programmatic SQL
DECLARE
Defines a cursor for a query
EXPLAIN
Describes the data access plan for a query
OPEN
Opens a cursor to retrieve query results
FETCH
Retrieves a row of query results
CLOSE
Closes a cursor
PREPARE
Prepares a SQL statement for dynamic execution
EXECUTE
Executes a SQL statement dynamically
DESCRIBE
Describes a prepared query
Запросы
All SQL statements have the same basic form:
Названия таблиц
wildcard
character
schema_n
ame
table_name
Названия колонок
wildcard
character
schema_n
ame
table_name
column_name
Use any of Integrated development environment (IDE) for working with SQL
Hardcore only..
Подключаемся к базе
1. MYSQL -u user –p
2. SHOW DATABASES;
данных
3. USE database_name;
4. SHOW TABLES;
– подключаемся к СУБД
– просмотр доступных баз
– переключение на нужную базу
– просмотр списка таблиц в базе
Selecting All Columns (SELECT *)
Selecting All Columns (SELECT *)
Duplicate Rows (DISTINCT)
Row Selection (WHERE)
• Comparison.
• Range.
• Set membership.
• Pattern matching.
• Null value.
The Comparison Test (=, <>, <, <=, >, >=)
The Comparison Test (=, <>, <, <=, >, >=)
The Range Test (BETWEEN)
The Range Test (BETWEEN)
The Set Membership Test (IN)
The Set Membership Test (IN)
The Pattern Matching Test (LIKE)
Wildcards patterns:
% - A substitute for zero or more characters
_ - A substitute for a single character
The Pattern Matching Test (LIKE)
Missing data (NULL values)
The Null Value Test (IS NULL)
The Null Value Test (IS NULL)
Compound Search Conditions (AND, OR, and NOT)
Compound Search Conditions (AND, OR, and NOT)
Sorting Query Results (ORDER BY Clause)
Sorting Query Results (ORDER BY Clause)
JOINS
JOIN это горизонтальное объединение
JOIN
INNER JOIN vs LEFT JOIN
UNION
Оператор
UNION
используется
для
объединения результата 2-х и более SELECT
запросов
UNION это вертикальное объединение
UNION ALL
UNION
Встроенные функции
• SQL aggregate functions return a single value,
calculated from values in a column.
• SQL scalar functions return a single value, based
on the input value.
CHAR_LENGTH()
Встроенные функции
• Useful aggregate functions:
• AVG() - Returns the average value
• COUNT() - Returns the number of rows
• MAX() - Returns the largest value
• MIN() - Returns the smallest value
• SUM() - Returns the sum
• Useful scalar functions:
• CHAR_LENGTH() - Returns the length of a text field in characters
• ROUND() - Rounds a numeric field to the number of decimals specified
• NOW() - Returns the current system date and time
• FORMAT() - Formats how a field is to be displayed
Агрегатные функции
Агрегатные функции (HAVING Clause)
Оператор HAVING был добавлен в SQL потому, что
оператор WHERE не может быть использован
вместе с агрегатной функцией
Псевдонимы (Aliases)
SQL
псевдонимы
используются
для
присваивания
таблице
или
столбцу
временного имени
Скаларные функции
Выражения
Вложенные запросы
Вопросы, давайте обсудим?
Практическое задание
1. Открываем cmd (Alt+Enter – развернуть на весь экран)
2. Подключаемся к linux серверу:
ssh tester@178.124.206.52
-> [Enter]
когда просит пароль (пароль при вводе не отображается!!!!!):
tester_pwd -> [Enter]
3. mysql -u voodoo_user –p
<– подключаемся к СУБД
 [Enter]
когда просит пароль : voodoo_pwd
4. Подключиться к базе данных voodoo: USE voodoo;
1. Выбрать фамилии всех сотрудников, имя
которых начинается на N
2. Выбрать названия товаров начинающиеся
на Z и названия компаний их поставляющих
3. * Выбрать все категории товаров, который
были отправлены в Torino, отсортировать в
алфавитном порядке
1.
2.
3.
4.
5.
linux host: ssh tester@178.124.206.52  [Enter]
pwd: tester_pwd
СУБД: mysql -u voodoo_user –p  [Enter]
pwd: voodoo_pwd
use voodoo; – выбор базы
show tables; – просмотр таблиц
select * from назв_таблицы; - просмотр структуры
таблицы
Download