MySQL Quick Review: Calculated Field and function

9.1 Calculated Field

Data stored in a database table format application program is generally not required. such as:

  • If you want to display in a field in both the company name, address and display a formula, but this information is generally contained in two different columns of the table.
  • City, state and zip code are stored in different columns, but the message label printing program as it takes them a proper field format retrieved.
  • Column data is mixed case, but the program requires reporting all data represented by capital.

In the example cited above, the data stored in the table is not required for the application. We need direct database retrieved conversion, calculated or formatted data; instead retrieve the data, then reformat the client application or reporting procedures.

So we need to calculate the field. Calculated fields are not actually stored in a database table, but runs created within a SELECT statement.

Here field (field) with substantially the same column (column) means, are often used interchangeably, but is generally referred to as column database column, and the term commonly used in the field is connected to the computing field.

It can be completed in a number of SQL statements and formatting conversion work can be done directly within the client application. In general, however, the completion of these operations than in the client complete much faster on the database server, because the DBMS is designed to quickly complete this process.

9.1.1 Calculation field using

For a title is created consisting of two simple examples.

vendors table contains the vendor name and location information. If you want to generate a report suppliers, vendors need to list the location of the format of such name (location) in the name of the supplier.

This report requires a single value, and the table data is stored in two columns and vend_country in vend_name. In addition, the need to use parentheses to enclose vend_country, these things are not explicitly stored in a database table. Take a look at how to write such a format with SELECT.

Splicing (CONCATENATE) coupled together to form a single value of values.

The solution is to splice together two columns. In MySQL SELECT statement can be used CONCAT () function to splice two columns.

Most DBMS implemented using || + or splice, and MySQL use Concat () function to implement. When converting SQL statement into MySQL statement must take this distinction in mind.

result:

SELECT CONCAT(vend_name, '(', vend_country, ')')
 FROM vendors
 ORDER BY vend_name;

Output:

+-------------------------------------------+
| CONCAT(vend_name, '(', vend_country, ')') |
+-------------------------------------------+
| ACME(USA)                                 |
| Anvils R Us(USA)                          |
| Jet Set(England)                          |
| LT Supplies(USA)                          |
+-------------------------------------------+
4 rows in set (0.06 sec)

Explanation:

  • CONCAT () splice sequence), i.e., the plurality of strings are connected to form a long string. CONCAT () requires one or more specific strings, between the respective string separated by commas. (Use back for more a function of speaking)
  • The above SELECT statement connecting the following four elements:
    • Vend_name name stored in the column;
    • Comprising a space and a left parenthesis string;
    • State is stored in vend_country column;
    • A string comprising a right parenthesis.

9.1.2 Using aliases

You get to perform on top of that statement, you will find the newly calculated column names, column names, column names long and significance can not be clearly seen. In fact, it is not the name, it's just a value. If you only look at the results of an SQL query tool, so nothing bad. However, an unnamed columns can not be used for client applications, because the client is no way to refer to it. This time it leads to SQL aliases.

Alias ​​(Alias) is the name of a field or replacement value. Alias ​​given by the AS keyword.

Using aliases modify the above SQL statement

SELECT CONCAT(vend_name, '(', vend_country, ')')
 AS vend_title
 FROM vendors
 ORDER BY vend_name;

AS may be omitted, as long as the latter need to rename a space.

SELECT CONCAT(vend_name, '(', vend_country, ')')
  vend_title
 FROM vendors
 ORDER BY vend_name;

Output:

+------------------+
| vend_title       |
+------------------+
| ACME(USA)        |
| Anvils R Us(USA) |
| Jet Set(England) |
| LT Supplies(USA) |
+------------------+
4 rows in set (0.06 sec)

So that any client can refer to this column by the alias, it appears to be an actual table column the same.

Aliases for more than a calculated field may also contain non-compliant characters in the actual table column names when renaming it (including spaces), which expanded upon vague or misunderstood the original name, and so on. But remember, not really going to rename the actual column names in the table.

Alias ​​sometimes called Export row (derived column), no matter what is called, they represent are the same thing.

9.1.3 perform arithmetic calculations

Another common use of calculated field is retrieved read data arithmetic. For example, an order table contains items order price price and item number quantity, the total price of items on request. Then only item price multiplied by data items can be.

SELECT order_id, order_price*order_quantiry 
 AS expanded_price
 FROM order;

MySQL arithmetic operators: +, -, *, /.

SELECT used to test by using the calculated field.

SELECT 2*3;

Summary: This paper describes how to create calculated fields and calculated fields. In addition, learn how to create and use an alias, so that applications can reference calculated fields.

9.2 Functions

SQL support the use of functions to process data.

Portability (portable): run code on multiple systems.
Most SQL statements are portable, while there are differences between SQL implementations, these differences are usually not so intractable. The portability function is not strong. Almost every major DBMS implementations are supported to achieve other functions that are not supported, and sometimes the difference is still very great.
For code portability, many SQL programmers deprecated features special implementation. While this is good, but do not use these functions, write some application code will be difficult.
If you decide to use the function, you should ensure good code comments, so that after you (or anyone else) can exactly know the meaning of SQL code written.

9.2.1 Use function

Most SQL implementation supports the following types of functions

  • For processing a text string (e.g., deletion or fill value, the conversion value of upper or lower case) a text function
  • Function values ​​for arithmetic operations on the value (e.g., returns the absolute value, algebraic operation).
  • Date and time functions for processing date and time values ​​and extracts a specific component from these values ​​(e.g., return the difference between the two dates, check the validity of the date, etc.).
  • DBMS being used to return specific information (such as user login information is returned, check the version details) of system function

9.2.2 text-processing functions

Previously introduced TRIM (): function to space. Similar functions are as follows:
Reference: novice tutorial

function Explanation Show
LEFT(s,n) Return the first n characters of the string s Returns a string runoob first two characters:SELECT LEFT('runoob',2) -- ru
RIGHT(s,n) After returning n characters string s After the return of the two-character string runoob:SELECT RIGHT('runoob',2) -- ob
LOWER(s) Converting the string to lowercase Lowercase string Runoob full turn: SELECT LOWER('Runoob') -- runoob
UPPER(s) The string converted to uppercase Returns a string runoob full speed lowercase:SELECT UPPER('Runoob') -- RUNOOB
TRIM(s) Remove string space around Remove blank spaces in the string space runoob:SELECT TRIM(' runoob ') -- runoob
LTRIM(s) Remove the string to the left of the space Remove the string left blank spaces runoob spaces:SELECT LTRIM(' runoob ') -- runoob空格
RTRIM(s) Remove the spaces on the right strings Remove the right box blank string runoob spaces:SELECT RTRIM(' runoob ') -- 空格runoob
SOUNDEX() Returns the value of a string SOUNDEX See explanation below
SUBSTRING(s, start, length) Length taken from the start position for the length of the string s substring 3 taken RUNOOB characters from a string in the second position:SELECT SUBSTRING("RUNOOB", 2, 3) AS ExtractString; -- UNO
LOCATE(s1,s) Obtaining from the start position of the string s s1 B acquires the position in the string abc: SELECT LOCATE('st','myteststring'); -- 5Returns a string abc in position b:SELECT LOCATE('b', 'abc') -- 2
LENGTH() Returns the string length Returns the length of the string runoob:SELECT LENGTH('runoob') -- 6

The above need further explanation SOUNDEX: SOUNDEX is a text string and any description of the algorithm which is converted to a phonetic representation of the alphanumeric mode. SOUNDEX consider a similar character and syllable pronunciation, makes it possible to compare pronunciation string comparison instead of letters. Although SOUNDEX not SQL concept, but MySQL (as big as DBMS) provide support for the SOUNDEX.

For example, create a table named customers, the table contains the customer (cust_name) and contact name (cust_contact).

CREATE TABLE customers(
    cust_name varchar(20) PRIMARY KEY,
    cust_contact varchar(20)
);

Now suppose a customer Coyote Inc., its contact named Y.Lee. But if this is the result of a mistake, this contact name should actually be Y.Lie, how do? Obviously, the correct contact search by name does not return data, as follows:

SELECT cust_name, cust_contact
FROM customers
WHERE cust_contact = 'Y.Lie';

Output:

Empty set

Now try using SOUNDEX () function to search, it matches all the pronunciation is similar to Y.Lie Contact name:

SELECT cust_name, cust_contact
FROM customers
WHERE SOUNDEX(cust_contact) = SOUNDEX('Y.Lie');

Output:

+-------------+--------------+
| cust_name   | cust_contact |
+-------------+--------------+
| Coyote Inc. | Y.Lee        |
+-------------+--------------+
1 row in set (0.05 sec)

In this example, WHERE clause SOUNDEX () function to convert cust_contact column values ​​and the search string to their SOUNDEX values. Since similar Y.Lee f Y.lie, so their SOUNDEX values ​​match, and therefore the WHERE clause properly filter the desired data.

9.2.3 The date and time handling functions

The date and time with the corresponding data type and stored in a special format for fast and efficient sorting or filtering, and save the physical storage space.

In general, the application does not use the format to store the date and time, and therefore a function of date and time is always used to read and process the statistical values. So, a very important date and time functions in MySQL language.

Reprinted form: rookie Tutorial

function Explanation Show
ADDDATE(d,n) D is calculated start date date plus n days SELECT ADDDATE("2020-01-15", 3);Or
SELECT ADDDATE("2020-01-15", INTERVAL 3 DAY);
-> (2020-01-18)
ADDTIME(t,n) N plus the time t seconds SELECT ADDTIME('2011-11-11 11:11:11', 5);
-> 2011-11-11 11:11:16 (sec)
CURDATE () Returns the current date SELECT CURDATE();
->2020-01-15
CURTIME () Returns the current time SELECT CURTIME();
->16:41:01
DATE() Date value extracted from the date or time expression SELECT DATE("2020-01-15");
->2020-01-15
DATEDIFF(d1,d2) Number of days between the date calculated d1-> d2 is SELECT DATEDIFF("2020-01-15","2020-01-4");
-> 11 (front date minus the date later)
DATE_ADD(d,INTERVAL expr type) D is calculated by the date after the date of the start of a period of time SELECT ADDDATE('2011-11-11 11:11:11',1);
-> 2011-11-12 11:11:11 (default is the day)
SELECT ADDDATE('2011-11-11 11:11:11', INTERVAL 5 MINUTE);
-> 2011-11-11 11:16:11 (TYPE function to the values listed above that similar)
DATE_FORMAT(d,f) Required display date expression f d SELECT DATE_FORMAT('2011-11-11 11:11:11','%Y-%m-%d %r')
-> 2011-11-11 11:11:11 AM
DAY(d) Returns the date part of the date value d SELECT DAY("2020-01-15");
-> 15
DAYOFWEEK (d) Date d day is today, 1 Sunday, 2 Monday, and so on SELECT DAYOFWEEK("2020-01-15");
-> 4
HOUR(t) Returns the hour of t SELECT HOUR("2020-01-15 17:21");
-> 17
MINUTE(t) Returns the value of t in minutes SELECT MINUTE("2020-01-15 17:21");
-> 21
MONTH(d) Returns the month of the date d, 1-12 SELECT MONTH("2020-01-15 17:21");
-> 1
NOW() Returns the current date and time SELECT NOW();
-> 2020-01-15 17:24:18
MICROSECOND(date) Number of microseconds corresponding date parameter SELECT MICROSECOND("2017-06-20 09:34:00.000023");
-> -> 23
TIME(expression) Extract the time portion of the incoming expression SELECT TIME("19:30:10");
-> 19:30:10
YEAR(t) Returns the date in year t SELECT YEAR("2020-01-15 17:21");
-> 2020

More Reference: rookie Tutorial

需要注意的是MySQL使用的日期格式。无论是什么时候指定一个日期,或是插入或更新等,日期必须为格式yyyy-mm-dd。所以,2020年1月15号,给出的是2020-01-15.虽然其他的日期格式可能也行,但这是首选的日期格式,因为它排除了多义性(如,04/05/06是2006年5月4号还是2006年4月5号或...)。

应该总是使用4位数字的年份。MySQL虽然支持2位数字的年份,比如处理00-69位2000-2069。虽然它们可能是打算要的年份,但使用完整的4位数字年份更可靠。

在数据库表中检索时间日期,比如:

SELECT cust_id, order_num
FROM orders
WHERE order_date = '2005-09-01';

这样写的 order_date = '2005-09-01' 可靠吗?如果order_date的数据类型是datetime,这种类型存储日期及时间值,那么在例表中的值全都具有时间值00:00:00,但实际上很可能并不总是这样。如果用当前日期和时间存储订单日期(因此我们得知道订单日期和下订单当前的时间),怎么办??比如,存储的order_date值为2005-09-01 11:30:05,则WHERE order_date = '2005-09-01'就失败。

解决的方式:让MySQL仅将给出的日期与列中的日期部分进行比较,而不是将给出的日期与整个列值进行比较。所以得使用DATE()函数。DATE(order_date)表示MySQL仅提取列的日期部分,所以修改如下:

SELECT cust_id, order_num
FROM orders
WHERE DATE(order_date) = '2005-09-01';

所以,对于日期的数据要特别注意,如果要的是日期,使用DATE(),如果要的是天,使用DAY(),如果要的是月,使用MONTH()等。最好明确要的是什么格式的日期,即使知道相应的列只包含日期也应该加上函数。

还有一种日期比较需要说明。如果要检索2005年9月下的所有订单,怎么办??简单的相等测试肯定不行,因为它也要匹配月份中的天数。提供以下的解决方法:

SELECT cust_id, order_num
FROM orders
WHERE DATE(order_date) BETWEEN '2005-09-01' AND '2005-09-30';

其中,BETWEEN操作符用来把2005-09-01和2005-09-30定义为一个要匹配的日期范围。
还有另一种:

SELECT cust_id, order_num
FROM orders
WHERE YEAR(order_date) = 2005 AND MONTH(order_date) = 9;

解释:YEAR()是一个从日期(或日期时间)中返回年份的函数。类似,MONTH从日期中返回月份。因此WHERE YEAR(order_date) = 2005 AND MONTH(order_date) = 9检索出order_date为2005年9月的所有行。

9.2.3 数值处理函数

数值处理函数仅处理数值数据。一般主要用于代数、三角或几何运算。

在主要DBMS的函数中,数值函数是最统一最一致的函数。

函数 说明
ABS(t) 返回数t的绝对值
COS(t) 返回角度为t的余弦
EXP(t) 返回数t的指数值
MOD(a, b) 返回除操作(a/b)的余数 = (a%b)
PI() 返回圆周率
RAND() 返回一个随机数
SIN(t) 返回角度为t的正弦
SQRT(t) 返回数t的平方根
TAN(t) 返回角度为t的正切

小结:介绍了如何使用SQL的数据处理函数,主要注意日期函数的使用。这些函数不需要死记硬背,忘了就拿出来看。当然,最好简单的函数就记一记,比如:ABS()、SQRT()、YEAR()、HOUR()、DAY()等这些。

Guess you like

Origin www.cnblogs.com/flunggg/p/12200198.html