Читаем MySQL: руководство профессионала полностью

+------------+-------------+

| 3 | -3 |

+------------+-------------+


Однако, округление для значений с плавающей запятой использует библиотеку C, которая на многих системах использует другую логику работы:


mysql> SELECT ROUND(2.5E0), ROUND(-2.5E0);

+--------------+---------------+

| ROUND(2.5E0) | ROUND(-2.5E0) |

+--------------+---------------+

| 2 | -2 |

+--------------+---------------+


Пример 4. В строгом режиме вставка значения, которое является слишком большим, приводит к переполнению и ошибке, а не к усечению до допустимого значения. Когда MySQL не выполняется в строгом режиме, происходит усечение к допустимому значению:


mysql> SET sql_mode='';

Query OK, 0 rows affected (0.00 sec)


mysql> CREATE TABLE t (i TINYINT);

Query OK, 0 rows affected (0.01 sec)


mysql> INSERT INTO t SET i = 128;

Query OK, 1 row affected, 1 warning (0.00 sec)


mysql> SELECT i FROM t;

+------+

| i |

+------+

| 127 |

+------+

1 row in set (0.00 sec)


Однако, условие переполнения происходит, если включен строгий режим:


mysql> SET sql_mode='STRICT_ALL_TABLES';

Query OK, 0 rows affected (0.00 sec)


mysql> CREATE TABLE t (i TINYINT);

Query OK, 0 rows affected (0.00 sec)


mysql> INSERT INTO t SET i = 128;

ERROR 1264 (22003): Out of range value adjusted for column 'i' at row 1


mysql> SELECT i FROM t;

Empty set (0.00 sec)


Пример 5: В строгом режиме и с настройкой ERROR_FOR_DIVISION_BY_ZERO деление на нуль вызывает ошибку, а не результат NULL.

В нестрогом режиме деление на нуль имеет результат NULL:


mysql> SET sql_mode='';

Query OK, 0 rows affected (0.01 sec)


mysql> CREATE TABLE t (i TINYINT);

Query OK, 0 rows affected (0.00 sec)


mysql> INSERT INTO t SET i = 1 / 0;

Query OK, 1 row affected (0.00 sec)


mysql> SELECT i FROM t;

+------+

| i |

+------+

| NULL |

+------+

1 row in set (0.03 sec)


Однако, деление на нуль выдает ошибку, если соответствующие SQL-режимы активны:


mysql> SET sql_mode='STRICT_ALL_TABLES,ERROR_FOR_DIVISION_BY_ZERO';

Query OK, 0 rows affected (0.00 sec)


mysql> CREATE TABLE t (i TINYINT);

Query OK, 0 rows affected (0.00 sec)


mysql> INSERT INTO t SET i = 1 / 0;

ERROR 1365 (22012): Division by 0


mysql> SELECT i FROM t;

Empty set (0.01 sec)


Пример 6. До MySQL 5.0.3 литералы с точным значением и с приблизительным значением преобразованы в значения с плавающей запятой двойной точности:


mysql> SELECT VERSION();

+------------+

| VERSION() |

+------------+

| 4.1.18-log |

+------------+

1 row in set (0.01 sec)


mysql> CREATE TABLE t SELECT 2.5 AS a, 25E-1 AS b;

Query OK, 1 row affected (0.07 sec)

Records: 1 Duplicates: 0 Warnings: 0


mysql> DESCRIBE t;

+-------+-------------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |

+-------+-------------+------+-----+---------+-------+

| a | double(3,1) | | | 0.0 | |

| b | double | | | 0 | |

+-------+-------------+------+-----+---------+-------+

2 rows in set (0.04 sec)


Начиная с MySQL 5.0.3, литерал с приблизительным значением все еще преобразован в значение с плавающей запятой, но литерал с точным значением обработан как DECIMAL:


mysql> SELECT VERSION();

+-----------------+

| VERSION() |

+-----------------+

| 5.1.6-alpha-log |

+-----------------+

1 row in set (0.11 sec)


mysql> CREATE TABLE t SELECT 2.5 AS a, 25E-1 AS b;

Query OK, 1 row affected (0.01 sec)

Records: 1 Duplicates: 0 Warnings: 0


mysql> DESCRIBE t;

+-------+-----------------------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |

+-------+-----------------------+------+-----+---------+-------+

| a | decimal(2,1) unsigned | NO | | 0.0 | |

| b | double | NO | | 0 | |

+-------+-----------------------+------+-----+---------+-------+

2 rows in set (0.01 sec)


Пример 7. Если параметр функции точный числовой тип, результат также точный числовой тип, с масштабом по крайней мере, как у параметра. Рассмотрите эти инструкции:


mysql> CREATE TABLE t (i INT, d DECIMAL, f FLOAT);

mysql> INSERT INTO t VALUES(1,1,1);

mysql> CREATE TABLE y SELECT AVG(i), AVG(d), AVG(f) FROM t;


Результаты до MySQL 5.0.3:


mysql> DESCRIBE y;

+--------+--------------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |

+--------+--------------+------+-----+---------+-------+

| AVG(i) | double(17,4) | YES | | NULL | |

| AVG(d) | double(17,4) | YES | | NULL | |

| AVG(f) | double | YES | | NULL | |

+--------+--------------+------+-----+---------+-------+


Результат двойной точности, независимо от типа параметра. А вот результаты в MySQL 5.0.3 и выше:

mysql> DESCRIBE y;

+--------+---------------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |

+--------+---------------+------+-----+---------+-------+

Перейти на страницу:

Похожие книги

C# 4.0: полное руководство
C# 4.0: полное руководство

В этом полном руководстве по C# 4.0 - языку программирования, разработанному специально для среды .NET, - детально рассмотрены все основные средства языка: типы данных, операторы, управляющие операторы, классы, интерфейсы, методы, делегаты, индексаторы, события, указатели, обобщения, коллекции, основные библиотеки классов, средства многопоточного программирования и директивы препроцессора. Подробно описаны новые возможности C#, в том числе PLINQ, библиотека TPL, динамический тип данных, а также именованные и необязательные аргументы. Это справочное пособие снабжено массой полезных советов авторитетного автора и сотнями примеров программ с комментариями, благодаря которым они становятся понятными любому читателю независимо от уровня его подготовки. Книга рассчитана на широкий круг читателей, интересующихся программированием на C#.Введите сюда краткую аннотацию

Герберт Шилдт

Программирование, программы, базы данных
C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных
Programming with POSIX® Threads
Programming with POSIX® Threads

With this practical book, you will attain a solid understanding of threads and will discover how to put this powerful mode of programming to work in real-world applications. The primary advantage of threaded programming is that it enables your applications to accomplish more than one task at the same time by using the number-crunching power of multiprocessor parallelism and by automatically exploiting I/O concurrency in your code, even on a single processor machine. The result: applications that are faster, more responsive to users, and often easier to maintain. Threaded programming is particularly well suited to network programming where it helps alleviate the bottleneck of slow network I/O. This book offers an in-depth description of the IEEE operating system interface standard, POSIX (Portable Operating System Interface) threads, commonly called Pthreads. Written for experienced C programmers, but assuming no previous knowledge of threads, the book explains basic concepts such as asynchronous programming, the lifecycle of a thread, and synchronization. You then move to more advanced topics such as attributes objects, thread-specific data, and realtime scheduling. An entire chapter is devoted to "real code," with a look at barriers, read/write locks, the work queue manager, and how to utilize existing libraries. In addition, the book tackles one of the thorniest problems faced by thread programmers-debugging-with valuable suggestions on how to avoid code errors and performance problems from the outset. Numerous annotated examples are used to illustrate real-world concepts. A Pthreads mini-reference and a look at future standardization are also included.

David Butenhof

Программирование, программы, базы данных