Retrieving data
Retrieving a single row
/* 没有明确排序查询的结果,则返回的数据的顺序没有特殊意义 */
select prod_name from products;
Retrieve multiple columns
select prod_id,prod_name,prod_price from products;
Retrieve all columns
/* 如果给定一个通配符(*),则返回列表中的所有列。
列的顺序一般是列在表中定义出现的顺序。
检索不需要的列通常会降低检索和应用程序的性能
*/
select * from produts;
Different search row
Use DISTICNT keyword, this keyword indicates MYSQL return only different values.
select distinct vend_id from products;
Limit results
SELECT statement returns all matching rows
In order to return the specified rows, LIMIT clause may be used
LIMIT start, count; // start from the beginning of the count data; start counting from zero
select prod_name from products LIMIT 5; /* 检索前5行数据 */
Sort Your Data
Using the ORDER BY clause of a SELECT statement, according to the ranking of the retrieved data is needed
The retrieved data is not displayed in a purely random order. If no data is typically sorted ,, it will appear in the display order underlying tables. However, if the data subsequently been updated and deleted, this order will be affected MYSQL reuse reclaim storage space. Therefore, if the control is not clear, then, can not (and should not) depend on the sort order. Relational database design theory is that if you do not specify the sort order, you should not assume retrieved a meaningful order.
Sorting Data
select prod_name from products order by prod_name; /* 按照姓名顺序进行排序 */
Sort by multiple columns
To sort by multiple columns (as done when just select multiple columns) just specify the column name, column names separated by commas between the can
/*首先按照价格,然后按照名称进行排序*/
/* 仅在多个行具有相同的prod_price值时才对产品按prod_name进行排序。
如果prod_price列中所有的值都是唯一的,则不会按照prod_name排序
*/
select prod_id,prod_price,prod_name from products order by prod_price,prod_name;
Specify the sort direction
Data sorting is not limited to ascending order (A to Z), this is only the default sort order, the ORDER BY clause may be used in descending order (from A to Z) in descending order. For descending order, you must specify the DESC keyword.
/* 按价格以降序排序产品*/
select prod_id from products order by prod_price desc;
If you want to sort descending on multiple columns, you must specify the DESC keyword for each column.
DESC keyword is opposite to the ASC, you can specify it in the ascending order.
Filtering data
Database tables typically contain large amounts of data, rarely need to retrieve all the rows in the table.
Usually only a subset of the extracted data table necessary for the particular operation or report.
Retrieve only need to specify the required datasearch condition, The search condition is also known as filter criteria.
SELECT statement, the data is filtered according to specified search condition in the WHERE clause. WHERE clause is given after the table name
Check single value
select prod_name,prod_price from products where prod_price = 2.50;
Mismatch checks
select vend_id,prod_name from products where vend_id <>1003;
Range check
In order to examine a range of values, may be used BETWEEN operator.
select prod_name from products where prod_price between 5 AND 10;
Null check
When you create a table, the table where the designer can specify whether columns may not contain values. When a column that does not contain a value called contains a null value null
Non-NULL value that the field contains 0, the character string contains only spaces or different
select prod_name from products where prod_price is null;
AND operator
In order to filter by more than one column, the AND operator may be used to attach the WHERE clause conditions.
AND:It is used to indicate row satisfy all given retrieval conditions
select prod_id,prod_price from products where vernd_id = 1003 and prod_price <=10;
OR operator
OR:MySql line indicates a retrieval condition matches any
Evaluation order
The solution is clear packets corresponding parentheses operator
IN operator
IN operator to specify a range of conditions, in the range of each condition can be matched.
IN takes the list of legal values separated by commas, all within the parentheses.
select prod_name from products where vend_id in (1002,1003) order by prod_name;
NOT operator
NOT operator role: it denied any conditions after the heel.
/* 列出除1002和1003之外所有供应商制造的产品 */
select prod_name from products where vend_id NOT in (1002,1003) order by prod_name;
Wildcard filtration
Wildcard: the value to match a portion of the special characters
In order to use wildcards in the search clauses you must use the LIKE operator.
LIKE indicated MYSQL followed using wildcard matching search pattern rather than directly compare equal match.
No. wildcard%
In the search string,% appear to represent any character any number of times
/* 找出所有以词jet起头的产品 */
select prod_id from products where prod_name like 'jet%';
/* 匹配包含anvil的值,而不论它之前或之后出现什么字符 */
select prod_id from products where prod_name like '%anvil%';
/* 匹配以s起头以e结尾的所有产品 */
select prod_id from products where prod_name like 's%e';
- Wildcard
Only match a single character instead of multiple characters
Create calculated fields
We need to be retrieved directly from the database conversion, data calculations or formatting; instead of retrieving the data, and then the client application or reporting procedures and then reformat
Calculated field is created at runtime in a SELECT statement, it is not actually exist in the database
Splicing field
Splicing: connecting together constitute a single value to a value
MySQL in the SELECT clause, use Concat () function to splice two columns
select Concat(vend_name,'(',vend_country,')') from vendors order by vend_name;
Performs arithmetic calculation
Using a data processing function
Text handling functions
function | Features |
---|---|
Left() | Returns a string on the left |
Length() | Returns the length of the string |
Locate() | Find a substring of string |
Lower() | The string lowercase |
LTrim () | Remove the string to the left of the space |
Date and time handling functions
function | Features |
---|---|
AddDate() | Add a date (days, weeks) |
AddTime() | Add a time |
CURDATE () | Returns the current date |
CURTIME () | Returns the current time |
Date() | It returns the current date portion of datetime |
DateDiff() | Calculating the difference between two dates |
Aggregated data
We often need to aggregate data rather than what they actually retrieved, aims to provide a special function MySql. Using these functions, MySql query can be used to retrieve the data, for analysis and report generation. Examples of this type of retrieval are the following:
-
Determining the number of rows in the table (or a condition is satisfied or comprises a certain number of lines value)
-
Bank of China set the table and get
-
Find the maximum value of the table columns (or rows or certain of all rows), minimum and average
Aggregate functions: runs on the line group, and the calculation function returns a single value
function Explanation AVG() Returns the average of a column COUNT() Returns the number of rows of a column MAX() Returns the maximum value of a column MIN () Returns the minimum value of a column SUM() Returns the value of a column and
AVG () function
The AVG () is calculated by the number of rows of the table and calculates the sum of a particular column, the column average value is obtained;
AVG () function will ignore the rows column value is NULL
/**
返回products所有产品的平均价格
**/
SELECT AVG(PROD_PRICE) AS avg_price;
/*1003供应商的平均价格*/
SELECT AVG(PROD_PRICE) AS avg_price where vend_id=1003;
COUNT () function
COUNT () function is counted. Available COUNT () function to determine the number of rows in a table or meet certain conditions the number of rows
COUNT (*): the number of rows in the table is counted, regardless of the table column contains the null or non-null value
COUNT (columb): having a row value of a particular column counts NULL value is ignored.
/* 返回customers表中客户的总数*/
select count(*) as num_cust from customers;
MAX function
MAX () returns the largest value in the specified column
MAX () requires you to specify the column name
Ignore row column value is NULL
select max(prod_price) as max_price from products;
MIN function
MIN () returns the minimum value of the column
Ignore row column value is NULL
SUM function
The SUM () is used to specify and column values (total)
Aggregate functions to summarize data. MySQL supports a number of aggregate functions, you can use a variety of methods they use to return the desired result, these functions are efficiently designed, they return the result of the general re-client computing applications much faster than they
Packet data
It allows data packets into logical groups, so as to enable aggregation was calculated for each group.
Creating groups
Grouping is established in the GROUP BY clause of the SELECT statement.
/*
GROUP BY子句指示MySql按照vend_id排序并分组数据。
这导致对每个vend_id而不是整个表就散num_prod.
GROUP BY子句指示MySql子句指示MySQL分组数据,然后对每个组而不是整个结果集进行聚集。
*/
SELECT
VEND_ID,
COUNT(*) AS NUM_PRODS
FROM
PRODUCTS
GROUP BY VEND_ID ;
- GROUP BY clause can contain any number of columns. This enables nesting of the packet, to provide more detailed control of the data packets
- If the packet is nested in the GROUP BY clause, data packets will be aggregated on the last predetermined. In other words, when the establishment of a packet, all columns are designated with the calculation.
- GROUP BY clause, each column must be retrieved column or a valid expression.
- If the packet is a NULL value in the column, as a NULL packet is returned. If a NULL value in the column a plurality of rows, they will be divided into one group.
Packet filtering
In addition to external data packet can GROUP BY, MYSQl allows filtering packets, which packets include a predetermined, which exclude packets
WHERE filter row is not specified packet '
where the line filter, and the filtered packets HAVING
/* */
SELECT
cust_id,
COUNT(*) AS orders
FROM
orders
GROUP BY cust_id
HAVING COUNT(*) >= 2 ;
And having a difference where
where packet data is filtered before, HAVING filtered after the data packet.
WHERE excluding lines included in the packet, which may change the calculated value, thus affecting the HAVING clause to filter out packets based on these values
/* 具有2个(含)以上,价格为10(含)以上的产品 */
SELECT
vend_id,
COUNT(*) AS num_prods
FROM
products
WHERE prod_price >= 10 /*Where子句过滤所有prod_price至少为10的行 */
GROUP BY vend_id /* 按照vend_id分组数据 */
HAVING COUNT(*) >= 2 ; /* having子句过滤数据计数为2或2以上的分组 */
The order of the SELECT clause
SELECT
字段,计算字段
FROM
表
WHERE
xxxxxxx /* 行级过滤 */
GROUP BY /* 分组说明 */
xxxxx
HAVING /* 组级过滤 */
xxxxx
ORDER BY
xxxx /* 输出要排序顺序 */
LIMIT
xxxx /* 要检索的行数 */