Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
КП, АЛЕКСЕЙ КОВАЛЬЧУК, ОПК-313.docx
Скачиваний:
1
Добавлен:
01.07.2025
Размер:
3.49 Mб
Скачать

3.2 Реалізація бази даних

У процесі реалізації бази даних «Мобільний оператор» було створено п’ять таблиць, які повністю характеризують обрану предметну область. Головна таблиця має назву «abonent» і включає до себе усі абоненти, тобто усіх людей, котрі додані до бази. Ключовим полем є поле «id», котре автоматично збільшується на один з додаванням нового абонента. Щодо інших полей таблиці «abonent», то кожна людина (абонент) має:

  1. tarrif_id (тариф) – айді поточного тарифа (якщо нема -1);

  2. balance (баланс) – баланс;

  3. nomer (номер) – номер;

  4. activation_time_tariff (час) – час, коли абонент активував тариф;

У кожного абонента підключений тариф або його немає. Тариф представлений у вигляді окремої сутності.

Усі поля таблиці «tariff» зазначені у таблиці 3.1.

Таблиця 3.1 – Таблиця «tariff» бази даних «Мобільний оператор»

Ім’я поля

Тип даних

Опис

id

Integer

Номер типа, ключ

price

Float

Ціна за підключення

Якщо є тарифи, то повинні бути услуги, які входят до тарифу. Услуга представлена сутністю «service».

Усі поля таблиці «service» зазначені у таблиці 3.2.

Таблиця 3.2 – Таблиця «service» бази даних «Мобільний оператор»

Ім’я поля

Тип даних

Опис

id

Integer

Номер услуги, ключ

name

Varchar

Назва услуги

У різних тарифах можуть бути однакові услуги. Для цього була створена таблиця «tariff_service», в якій зберігається сукупність зав’язків тарифів і услуг. Ця сутність зображена у таблиці 3.3.

Таблиця 3.3 – Таблиця «tariff_service» бази даних «Мобільний оператор»

Ім’я поля

Тип даних

Опис

tariff_id

Integer

Номер тарифу

service_id

Integer

Номер услуги

price

Float

Ціна за використання одиниці услуги

Кожен абонент моє можливість відправляти смс повідомлення іншим абонентам. Це реалізовано в сутності «sms».

Усі поля таблиці «sms» зазначені у таблиці 3.4.

Таблиця 3.4 – Таблиця «User-person» бази даних «Мобільний оператор»

Ім’я поля

Тип даних

Опис

id

Integer

Номер sms, ключ

abonent_id

Integer

Номер відправника

text

Text

Текст повідомлення

abonent_to

Integer

Номер отримувача

time

Timestamp

Час відправлення

Основною можливістю мобільно оператора - це дзвонити іншим абонентам. Всі дзвінки зберігаються в історії. Для зберігання була творена таблиця «history».

Усі поля таблиці «history» зазначені у таблиці 3.5.

Таблиця 3.5 – Таблиця «history» бази даних «Мобільний оператор»

Ім’я поля

Тип даних

Опис

id

Integer

Номер дзвінка, ключ

abonent_id

Integer

Номер того, хто телефонує

duration

Integer

Тривалість дзвінка (секунди)

abonent_to

Integer

Номер приймаючого

time

Timestamp

Час дзвінка

Створені таблиці повністю відображають функціонування бази даних «Мобільний оператор» та відповідають усім бізнес-правилам. Наступним етапом виконання курсового проекту була генерація SQL-коду відповідної моделі даних, який викладений в додатку A. Також створена візуальна схема БД, яку показано в додатку Б.

3.3 Received results of working with database

3.3.1 Creating of queries

SQL is a special-purpose programming language designed for creating, modifying and managing data. SQL query is a call to a database, which executes the modifying, eliminating, sorting, receipt the data based on a special criteria and other manipulations with data. There are such SQL statements as ‘CREATE’, ‘INSERT’, ‘UPDATE’, ‘DELETE’ and others, but the most common operation in SQL is the query which is performed with the ‘SELECT’ statement. ‘SELECT’ retrieves data from one or more tables and it is the most complex statement in SQL, which includes such optional keywords and clauses as ‘FROM’, ‘WHERE’, ‘JOIN’, ‘GROUP BY’, ‘HAVING’, ‘ORDER BY’ and others.

The next step of completing my academic year project is creating queries for the considered application domain “Address book”.

The following query is an example of an‘INSERT’ query that adds data in the table “Person”.

INSERT INTO `person` (`Person_ID`, `Name`, `Surname`, `MiddleName`, `Email`, `Address`, `Mobile`, `Type_ID`) VALUES

(0,'Dmitriy','Andreychuk','Alekseevich','dima.andr@gmail.com','Traktorostroiteley str, 140A, 128','0995674409',0),

(2,'Roman','Bezruchko','Jurievich','romab10@gmail.com','Konoplyana str, 76, 23','0673440945',0),

COMMIT;

The next ‘INSERT’ query fills data in the table “Role”.

INSERT INTO `role` (`Role_ID`, `RoleName`) VALUES

(0,'Guest'),

(1,'User'),

(2,'Admin');

COMMIT;

There were the simplest examples of an ‘INSERT’ query. With the statement ‘INSERT’ it is also possible to build more difficult queries, for example to use INSERT INTO <target_table> SELECT <columns> FROM <source_table> to efficiently transfer a large number of rows from one table, such as a staging table, to another table with minimal logging.

This type of query was used to create a backup table of table “User”.

INSERT INTO `Users_backup` (`User_ID`, `UserName`, `UserSurname`, `UserEmail`, `Password`, `Role_ID`)

SELECT *

FROM `Users`

COMMIT;

This type of ‘INSERT’ query is also used with the certain restriction which can be defined by the ‘WHERE’ clause. The following query will create a new table “Users_names”, which will contain names of all users, where ‘User_ID’ is more then ‘5’.

INSERT INTO `Users_names` (`User_ID`, `UserName`)

SELECT (`User_ID`, `UserName`)

FROM `Users`

WHERE `User_ID`>5

COMMIT;

The next SQL statement we will consider is ‘UPDATE’. The following ‘UPDATE’ query changes the value of ‘UserName’ field in the table “User_names”, where `User_ID` is ‘4’.

UPDATE `User_names`

set UserName = 'Anton'

WHERE User_ID = '4';

An ‘UPDATE’ query can be also used to change all values of ‘UserName’ field in this table, but without any restrictions.

UPDATE `User_names`

set UserName = 'Victor'

With the statement ‘UPDATE’ it is possible to use such clauses, as ‘WHERE EXISTS’, ‘SELECT’ and even more difficult operators like ‘INNER JOIN’. The following ‘UPDATE’ query changes all values of ‘UserName’ field in the table ‘User’ if ‘User_ID’ column from table ‘User’ corresponds with the ‘User_ID’ column from table ‘User’.

UPDATE `user`

SET UserName='Alex'

WHERE EXISTS (SELECT * FROM user_person

WHERE user.`User_ID` = user_person.`User_ID`)

An ‘UPDATE’ query can also be used to change more then one field. The following query changes values of several fields in the table ‘Person’.

UPDATE person

SET Mobile='0674558204', Email='bakhaaddini@gmail.com'

WHERE Person_ID = 1

The next SQL statement we will consider is ‘DELETE’. This type of query removes a record from any table you want. The following ‘DELETE’ query removes the value of the ‘Address’ column, where ‘Person_ID’ = ‘10’.

DELETE Address FROM `person`

WHERE Person_ID = 10

The WHERE clause specifies which record or records that should be deleted. If you omit the WHERE clause, all records will be deleted like in the following example.

DELETE FROM `user_person`

But this operation (deleting all rows) can be performed more quickly by using the special command ‘TRUNCATE TABLE’. If the table contains an identity column, the counter for that column is reset to the seed value defined for the column. If no seed was defined, the default value ‘1’ is used. ‘TRUNCATE TABLE’ removes all rows from a table, but the table structure and its columns, constraints, indexes, and so on remain. The following query removes all records from the ‘User_Person’ table.

TRUNCATE table `user_person`

The syntax of using ‘DELETE’ statement allows to include in query such clauses as ‘LIMIT’. In this case the delete operation is performed on a deletion of all rows defined with values in the ‘WHERE’ and ‘LIMIT’ constructions. The following example deletes 11 rows from the ‘User’ table beginning with the row where ‘User_ID’ value is ‘6’.

DELETE FROM `user`

WHERE User_ID > 5

LIMIT 11

The next SQL statement we will consider is ‘SELECT’. SQL ‘SELECT’ statement is used to fetch the data from a database table which returns data in the form of result table. These result tables are called result-sets. ‘SELECT’ is the mostly used SQL command. This type of query has many optional clauses:

  1. WHERE, that specifies which rows to retrieve.

  2. GROUP BY, which groups rows sharing a property so that an aggregate function can be applied to each group.

  3. HAVING, that selects among the groups defined by the ‘GROUP BY’ clause.

  4. ORDER BY, which specifies an order in which to return the rows.

  5. AS, which provides an alias which can be used to temporarily rename tables or columns.

The following query selects all fields from the table ‘Person’ and sorts this records by surname. This query has one restriction: a name of existing persons must be ‘Vladislav’.

SELECT *

FROM person

WHERE Name='Vladislav'

ORDER BY Surname;

The next query selects all records from the table ‘Person’ who has ‘Kyivstar’ as a mobile operator.

SELECT *

from person

WHERE Mobile LIKE '067%' OR Mobile LIKE '097%'

OR Mobile LIKE '098%' OR Mobile LIKE '096%'

ORDER BY Name

The result of this query is shown in a figure 3.1.

Figure 3.1 – The result of ‘SELECT’ query

The next ‘SELECT’ query contains a ‘COUNT AS’ construction. This query selects those names from the table ‘Person’ which meet more then once.

SELECT Name, COUNT(Name) AS 'Amount'

FROM person

GROUP BY Name

HAVING Amount > 1;

With the ‘SELECT’ statement it is also possible to use a ‘JOIN’ construction. The following query joins two tables – ‘User_Person’ and ‘User’. The new table consisting of rows of the first and second tables will be the result of this query.

SELECT user.`UserName`, `user`.`UserSurname`,

MAX(`user_person`.`MeetingDate`) AS LastDate

FROM user

JOIN user_person ON user.`User_ID`=user_person.`User_ID`

GROUP BY user.`UserName`, user.`UserSurname`

ORDER BY LastDate

The next type of queries we will consider is nested queries. Nested queries are queries which are contained in a body of other query. The following nested query consists of the ‘SELECT IN SELECT’ construction.

SELECT UserName, UserSurname

FROM user

WHERE User_ID IN

(SELECT User_ID

FROM user_person

WHERE Person_ID = 3)

The result of this query is shown on a figure 3.2.

Figure 3.2 – The result of the first nested query

It is possible to use more than one ‘SELECT IN SELECT’ construction if you need to use three or more tables to get a necessary data. The following example selects the type of person, which was created by user with value of the identifier equally ‘4’.

SELECT Value FROM type

WHERE Type_ID IN

(SELECT Type_ID

FROM person

WHERE Person_ID IN

(SELECT Person_ID

FROM user_person

WHERE User_ID = 4));

The result of this nested query is shown on a figure 3.3.

Figure 3.3 – The result of the second nested query

Syntax of nested queries allows to use even 'JOIN' constructions. The following example of nested queries connects three tables to obtain the necessary data – a name and a surname of the user and a name and a surname of the created person.

SELECT user.`UserName`, `user`.`UserSurname`,

MAX(user_person.`MeetingDate`) AS LastDate,

person.Name, person.`Surname`

FROM `user`

JOIN user_person ON user.User_ID = user_person.`User_ID`

JOIN person ON `user_person`.`Person_ID` = person.`Person_ID`

The result of this query is shown in a figure 3.4.

Figure 3.4 – The result of the third nested query

In conclusion we will consider the ‘JOIN’ queries. ‘JOIN’ constructions were used in the previous queries, but there were no examples of using ‘FULL OUTER JOIN’, ‘LEFT OUTER JOIN’ or ‘RIGHT OUTER JOIN’ statements. The following query is an example of ‘LEFT OUTER JOIN’ query, which connects two tables – ‘User’ and ‘Role’ to check which user has not a role.

SELECT * from user

LEFT OUTER JOIN role

ON user.`Role_ID`=role.`Role_ID`

WHERE RoleName IS NULL

There is not any user without a role in created tables, so the result of this query will be an empty table. This result is shown on a figure 3.5.

Figure 3.5 – The result of the first ‘JOIN’ query

The following query uses the ‘RIGHT OUTER JOIN’ statement. The results of this query show which type of person was never used by creating a ‘Person’ table.

SELECT Person_ID, Name, Surname, type.`Value`

FROM person

RIGHT OUTER JOIN type

ON person.`Type_ID`=type.`Type_ID`

The result of this ‘RIGHT OUTER JOIN’ query is shown on a figure 3.6.

Figure 3.6 – The result of the second ‘JOIN’ query

The following query selects those people who were created more than one time.

SELECT Name, COUNT(user_person.`Person_ID`) AS 'Amount'

FROM person

RIGHT OUTER JOIN user_person

ON person.`Person_ID`=user_person.`Person_ID`

GROUP BY user_person.`Person_ID`

HAVING Amount > 1

The result of this query is shown on a figure 3.7.

Figure 3.7 – The result of the third ‘JOIN’ query