mysql knowledge store -1

authority management

MySQL account information is stored in the mysql database.

USE mysql;
SELECT user FROM user;

create Account


CREATE USER myuser IDENTIFIED BY 'mypassword';

The newly created account does not have any permissions.

mysql constraint

If the primary key of table A is a field in table B, the field is called the foreign key of table B, table A is called the primary table, and table B is called the slave table. Foreign keys are used to achieve referential integrity. Different foreign key constraints will make the two tables closely combined, especially the cascade operation of modification or deletion will make daily maintenance easier. Take MySQL as an example to summarize the differences and connections between the three foreign key constraints.

  • primary key constraint
    • PRIMARY KEY
    • There can only be one primary key per table
    • The primary key ensures the uniqueness of the record, and the value of the primary key does not repeat
    • Primary key is automatically NOT NULL
    • SHWO COLUMNS FROM studentView table structure
  • unique constraint
    • UNIQUE KEY
    • Unique constraints guarantee the uniqueness of records
    • The field of the unique constraint can be null (NULL)
    • Each data table can have multiple unique constraints
  • default constraints
    • DEFAULT
    • When inserting a record, if a field is not explicitly assigned a value, a default value is automatically assigned
CREATE TABLE course(
id int AUTO_INCREMENT PRIMARY KEY,
cou_name varchar(20) NOT NULL UNIQUE KEY,
time int DEFAULT 40
);
  • foreign key constraints
    • FOREIGN KEY
    • Maintain data consistency and integrity
    • Implement 1-to-1 or 1-to-n relationships
    • Parent and child tables must use the same storage engine, and temporary tables are prohibited.
    • Foreign key columns and reference columns must have similar data types. The length of the digits or the signed bit must be the same; the length of the characters can be different.
    • Foreign key columns and reference columns must be indexed. If there is no index on the foreign key column, MySQL will automatically create an index
CREATE TABLE school(
id int AUTO_INCREMENT PRIMARY KEY,
sname varchar(20) NOT NULL
);
CREATE TABLE student2(
id int AUTO_INCREMENT PRIMARY KEY,
sid int,
FOREIGN KEY (sid) REFERENCES school(id) ON DELETE CASCADE  on update set null
);
  • Referencing operations for foreign key constraints
    • CASCADE : Delete or update from the parent table and automatically delete or update the matching row in the child table. The referenced column in the parent table deletes a certain data, and the row of the corresponding data is deleted in the child table.
CREATE TABLE student3(
id int AUTO_INCREMENT PRIMARY KEY,
sid int,
FOREIGN KEY (sid) REFERENCES school(id) ON DELETE CASCADE on update set null
); 

insert data

#插入一行数据
INSERT INTO table(column1,column2...)
VALUES (value1,value2,....);
#插入多行数据 
INSERT INTO table(column1,column2...)
VALUES (value1,value2,...),
       (value1,value2,...),
...;
# 使用SELECT语句返回的列和值来填充INSERT语句的值
INSERT INTO table_1
SELECT c1, c2, FROM table_2;

Copy table

#不会复制外键
CREATE TABLE tasks_bak LIKE tasks;

INSERT INTO tasks_bak
SELECT * FROM tasks;


Modify table

  • Add column to table
ALTER TABLE table_name 
add column_name datatype;
#给学生表增加学号这一列
ALTER TABLE student1
add stu_id int;
  • delete column from table
alter table table_name
drop column column_name

  • Modify a column in a table
--MySQL
alter table table_name
modify column column_name datatype;
--sql server
alter table table_name
alter column column_name datatype;
  • Define a foreign key to bind the stu_id of the student1 table to the sid of sutdent2 and name it fk_student_id
ALTER TABLE student1
ADD CONSTRAINT fk_student_id FOREIGN KEY(stu_id)
REFERENCES student2 (sid);

sql syntax

  • Inquire

SELECT 
    column_1, column_2, ...
FROM
    table_1
[INNER | LEFT |RIGHT] JOIN table_2 ON conditions
WHERE
    conditions
GROUP BY column_1
HAVING group_conditions
ORDER BY column_1
LIMIT offset, length;
  • SELECT is followed by a comma-separated list of columns or an asterisk (*), indicating that all columns are to be returned.

  • FROM specifies the table or view for which data is to be queried.

  • JOIN fetches data from other tables based on some join conditions. (Do not understand the self-query of the connection)

  • WHERE filters the rows in the result set.

  • GROUP BY combines a set of rows into small groupings and applies an aggregate function to each small grouping.

  • HAVING filters are based on small groupings defined by the GROUP BY clause.

  • ORDER BY specifies a list of columns to use for sorting.

  • LIMIT limits the number of rows returned.

  • Filtering Unfiltered data is very large, causing a lot of redundant data to be transmitted over the network, wasting network bandwidth. So try to use SQL statements to filter unnecessary data, instead of transmitting all the data to the client and then filtering by the client. IS NULL is a NULL value. Try other syntaxes by yourself, which is relatively simple

SELECT * FROM `school`
WHERE sname IS NOT NULL;
SELECT * FROM `school`
WHERE sname IS  NULL;

It should be noted that NULL is not the same as 0 or the empty string.

AND OR is used to join multiple filter conditions. The AND is handled first, so when a filter expression involves multiple ANDs and ORs, () should be used to determine the priority.

The IN operator is used to match a set of values, and can also be followed by a SELECT clause to match a set of values ​​obtained by a subquery.

The NOT operator is used to negate a condition.

  • Wildcards Wildcards are also used in filter statements, but only for text fields.

% matches >=0 arbitrary characters, similar to *;

_ matches == 1 arbitrary character, similar to .; (matches only one character)

[ ] matches characters within a set, eg [ab] will match the characters a or b. Use the caret ^ to negate it, i.e. not match the characters in the set. Use Like for wildcard matching.

SELECT *
FROM mytable
WHERE col LIKE '[^AB]%'; -- 不以 A 和 B 开头的任意文本

SELECT *
FROM mytable
WHERE col LIKE '%AB%'; --匹配任何位置包含文本 AB的值
  • regular expression
  1. Basic character matching

Retrieve all records containing D in the lastname. The default is case insensitive. For case sensitivity, you can use BINARY

SELECT firstname,lastname,officeCode
FROM employees
WHERE lastname REGEXP BINARY 'D';
  1. Any character match (. matches any single character except \n)
SELECT firstname,lastname,employeeNumber
fROM employees
WHERE employeeNumber REGEXP '.02';
  1. make or configure
SELECT firstname,lastname,officeCode
FROM employees
WHERE officeCode REGEXP '1|2|3';--检索officecode为1或者2或者3的记录

另一种写法

SELECT firstname,lastname,officeCode
FROM employees
WHERE officeCode REGEXP '[123]';--等价于[1|2|3]
  1. remove some elements()
SELECT firstname,lastname,officeCode
FROM employees
WHERE officeCode REGEXP '[^123]';--不包含1或2或3的记录


  1. The matching range [] matches several characters so that [0123456789] can match 0 to 9, [1-4] [4-9] is also a legal range. Also, ranges don't have to be numeric only, [az] matches any alphabetic character
SELECT firstname,lastname,officeCode
FROM employees
WHERE officeCode REGEXP '[1-4]'; --等同于[1234]
  1. ^ matches the beginning of the string
select name from 表名 where name REGEXP '^hello';
  1. $ matches the end of the string
select name from 表名 where name REGEXP 'hello$';
  1. [^...], match characters not included in [] Match characters not included in [], such as querying names other than hello
 SELECT prod_name FROM products WHERE prod_name REGEXP '[^hello]';
  1. To match special characters use \ to escape
expression match content
\\. can match.
\\f form feed
\\n newline
\\r Enter
\\t Tabs
  1. match character class
expression Configuration content
[:alnum:] Any letters and numbers (through [a-zA-Z0-9])
[:alpha:] Any character (same as [a-zA-Z])
[:blank:] spaces and tabs (same as [\\t])
[:digit:] Any number (same as [0-9])
[:lower:] any lowercase letter
[:upper:] any capital letter
[:space:] any whitespace character including spaces
  1. Matching multiple instances, regarding repeating metacharacters
expression Configuration content
* 0 or more matches
+ 1 or more matches (equal to {1,})
1 or more matches (equal to {0,1})
{n} specified number of matches
{n,} no less than the specified number of matches
{n,m} The range of matching numbers (m does not exceed 255)
  1. Actual Liezi
  • Application example to find user records with malformed Email in the user table:

SELECT * 
FROM users
WHERE email NOT REGEXP '^[A-Z0-9._%-]+@[A-Z0-9.-]+.[A-Z]{2,4}$'

The syntax of regular expressions in the MySQL database mainly includes the meanings of various symbols.

  • (^) character

The starting position of the matching string, such as "^a" means a string starting with the letter a.


mysql> select 'xxxyyy' regexp '^xx';

+-----------------------+
| 'xxxyyy' regexp '^xx' |
+-----------------------+
|           1 |
+-----------------------+
1 row in set (0.00 sec)

Query whether the string xxxyyy starts with xx, and the result value is 1, indicating that the value is true and the condition is satisfied.

  • ($) character

Matches the end position of the string, such as "X^" for a string ending with the letter X.

  • (.)character

This character is the dot in English, which matches any character, including carriage return, line feed, etc.

  • (*)character

The asterisk matches 0 or more characters, there must be content before it. Such as:

mysql> select 'xxxyyy' regexp 'x*';

This SQL statement, the regular match is true.

  • (+) character

The plus sign matches 1 or more characters and must also have content before it. The use of the plus sign is similar to that of the asterisk, except that the asterisk is allowed to appear 0 times, and the plus sign must appear at least once.

  • (?)character

The question mark matches 0 or 1 times.

Example:

Now according to the above table, various different types of SQL queries can be installed to meet the requirements. Some understandings are listed here. Consider we have a table called person_tbl and a field called name:

Query to find all names starting with 'st'

mysql> SELECT name FROM person_tbl WHERE name REGEXP '^st';

Query to find all names ending with 'ok'

mysql> SELECT name FROM person_tbl WHERE name REGEXP 'ok$';

The query finds all strings whose name contains the function 'mar'

mysql> SELECT name FROM person_tbl WHERE name REGEXP 'mar';

Query to find all names starting with a vowel and ending with 'ok'

mysql> SELECT name FROM person_tbl WHERE name REGEXP '^[aeiou]|ok$';

A regular expression can use the following reserved words ^ The matched string begins with the following string

mysql> select "fonfo" REGEXP "^fo$"; -> 0(表示不匹配) 
mysql> select "fofo" REGEXP "^fo"; -> 1(表示匹配)

$ matches the string that ends with the previous string

mysql> select "fono" REGEXP "^fono$"; -> 1(表示匹配) 
mysql> select "fono" REGEXP "^fo$"; -> 0(表示不匹配) 

. matches any character (including newlines)

mysql> select "fofo" REGEXP "^f.*"; -> 1(表示匹配) 
mysql> select "fonfo" REGEXP "^f.*"; -> 1(表示匹配)

a* matches any number of a (including the empty string)

mysql> select "Ban" REGEXP "^Ba*n"; -> 1(表示匹配) 
mysql> select "Baaan" REGEXP "^Ba*n"; -> 1(表示匹配) 
mysql> select "Bn" REGEXP "^Ba*n"; -> 1(表示匹配)

a+ matches any number of a (excluding the empty string)


mysql> select "Ban" REGEXP "^Ba+n"; -> 1(表示匹配) 
mysql> select "Bn" REGEXP "^Ba+n"; -> 0(表示不匹配) 

a? matches one or zero a's

mysql> select "Bn" REGEXP "^Ba?n"; -> 1(表示匹配) 
mysql> select "Ban" REGEXP "^Ba?n"; -> 1(表示匹配) 
mysql> select "Baan" REGEXP "^Ba?n"; -> 0(表示不匹配)

de|abc matches de or abc


mysql> select "pi" REGEXP "pi|apa"; -> 1(表示匹配) 
mysql> select "axe" REGEXP "pi|apa"; -> 0(表示不匹配) 
mysql> select "apa" REGEXP "pi|apa"; -> 1(表示匹配) 
mysql> select "apa" REGEXP "^(pi|apa)$"; -> 1(表示匹配) 
mysql> select "pi" REGEXP "^(pi|apa)$"; -> 1(表示匹配) 
mysql> select "pix" REGEXP "^(pi|apa)$"; -> 0(表示不匹配)

(abc)* matches any number of abc (including the empty string)

mysql> select "pi" REGEXP "^(pi)*$"; -> 1(表示匹配) 
mysql> select "pip" REGEXP "^(pi)*$"; -> 0(表示不匹配) 
mysql> select "pipi" REGEXP "^(pi)*$"; -> 1(表示匹配) 

{1} {2,3}

This is a more comprehensive method, which can achieve the functions of several of the previous reserved words

a*

can be written as a{0,}

a+

can be written as a{1,}

a?

can be written as a{0,1}

There is only one integer parameter i in {}, indicating that the character can only appear i times; there is an integer parameter i in {}, followed by a ",", indicating that the character can appear i times or more; in {} There is only one integer parameter i in }, followed by a ",", followed by an integer parameter j, indicating that the character can only appear more than i times and less than j times (including i times and j times). The integer parameter must be greater than or equal to 0 and less than or equal to RE_DUP_MAX (default is 255). If there are two parameters, the second must be greater than or equal to the first

[a-dX]

Matches "a", "b", "c", "d" or "X"

[^a-dX]

Matches any character except "a", "b", "c", "d", "X".

"[", "]" must be used in pairs


mysql> select "aXbc" REGEXP "[a-dXYZ]"; -> 1(表示匹配) 
mysql> select "aXbc" REGEXP "^[a-dXYZ]$"; -> 0(表示不匹配) 
mysql> select "aXbc" REGEXP "^[a-dXYZ]+$"; -> 1(表示匹配) 
mysql> select "aXbc" REGEXP "^[^a-dXYZ]+$"; -> 0(表示不匹配) 
mysql> select "gheis" REGEXP "^[^a-dXYZ]+$"; -> 1(表示匹配) 
mysql> select "gheisa" REGEXP "^[^a-dXYZ]+$"; -> 0(表示不匹配)

subquery

Data for only one field can be returned in a subquery.

You can use the result of a subquery as a filter condition for a WHRER statement:


SELECT *
FROM mytable1
WHERE col1 IN (SELECT col2
                 FROM mytable2);
                 
SELECT cust_name, (SELECT COUNT(*)
                   FROM Orders
                   WHERE Orders.cust_id = Customers.cust_id)
                   AS orders_num
FROM Customers
ORDER BY cust_name;                 

Combined query

  • Two base cases require the use of combined queries: (1) return similarly structured data from different tables in a single query (2) - perform multiple queries on a single table, returning data as a single query
  • Use UNION to combine two queries, if the first query returns M rows and the second query returns N rows, then the result of the combined query is M+N rows.
  • Each query must contain the same columns, expressions, or aggregate functions.
  • By default, the same line will be removed. If you need to keep the same line, use UNION ALL. The default is equivalent to a union
  • There can only be one ORDER BY clause, and it must be at the end of the statement. Column data types need to be compatible
SELECT col
FROM mytable
WHERE col > 1
UNION
SELECT col
FROM mytable
WHERE col <5;
ORDER BY col;

等同于
SELECT col
FROM mytable
WHERE col >1 and col<5;
ORDER BY col;

Field calculation connection processing

  • concat() Concat() is used to concatenate two fields. Many databases will use spaces to pad a value to the column width, so the result of the concatenation will have some unnecessary spaces. Use Trim() to remove leading and trailing spaces. Also supports Rtrim() (remove spaces on the right) LTrim() removes spaces on the left
# 查询员工表,返回结果合并lastname和firstname,设置别名为AS
SELECT Concat(Trim(lastname),Trim(firstname)) AS ename
FROM employees;

#  - + - * /来对查询的字段进行计算
SELECT id,
      quantity,
      item_price,
      quantity*item_price AS expanded_price --数量与单价乘积
FROM products
WHERE id = 100;

text processing functions

  • LEFT()
    is used to return the character on the left side of the string. The function has two parameters, the first parameter is a string, and the second parameter is the string length. If the length of the string is 2, two strings are intercepted from the left side of the string and returned.
SELECT id,LEFT(content,3) AS left_content FROM fun_text WHERE id='1'
  • LOCATE() returns the position of the first occurrence of a string within another string, or 0 if not found.
SELECT id,LOCATE('234', content) AS locate_content FROM fun_text WHERE id='1';
#content 为表中的一列
  • LOWER() converts the string to all lowercase letters.

  • TRIM() removes spaces from both sides of a string.

  • SUBSTRING() String interception function. This function is similar to the LEFT() and RIGHT() functions, both of which can intercept strings, but with more powerful functions.

1. Start intercepting from the Nth string

SELECT id,SUBSTRING(content,5) AS sub_content FROM fun_text WHERE id='1';

2. Start intercepting from the Nth string, intercepting M characters (including n)

SELECT id,SUBSTRING(content,5,2) AS sub_content FROM fun_text WHERE id='1';
  • SOUNDEX() Finally, say something different from the previous character processing function SOUNDEX(), this function can convert the pronunciation of a word into a word with a similar pronunciation. Simply put, it means to convert the dialect into Mandarin. This is very useful in search.
SELECT * FROM fun_text WHERE SOUNDEX(content) = SOUNDEX('lie');

lie is not equal to lee, but SOUNDEX(content) = SOUNDEX('lie'), because the pronunciation of lie and lee are very similar.

Date and time handling

  • Date format: YYYY-MM-DD
  • Time format: HH:MM:SS
function illustrate
AddDate() Add a date (day, week, etc.)
AddTime() Add a time (hour, minute, etc.)
CurDate () Returns the current date
CurTime() return current time
Date() Returns the date part of a datetime
DateDiff() Calculate the difference between two dates
Date_Add() Highly flexible date arithmetic functions
Date_Format() Returns a formatted date or time string
Day() Returns the days part of a date
DayOfWeek () For a date, returns the corresponding day of the week
Hour() Returns the hour part of a time
Minute() Returns the minute part of a time
Month() Returns the month part of a date
Now() Returns the current date and time
Second() Returns the seconds part of a time
Time() Returns the time part of a datetime
Year() Returns the year part of a date

Example application


SELECT DATE_ADD('2017-05-15 08:12:25', INTERVAL 1 DAY);#(DAY,MOUTH,YEAR)
#2017-05-16 08:12:25
SELECT FROM_UNIXTIME(1494815834, '%Y年%m月%d日 %h时%分:%s秒');
# 2017年05月15日 10时分:14秒
SELECT FROM_UNIXTIME(1494815834);-- 2017-05-15 10:37:14 
-- MySQL 拼凑日期、时间函数:makdedate(year,dayofyear), maketime(hour,minute,second)  
SELECT MAKEDATE(2017,31);   -- '2017-01-31'   
SELECT MAKEDATE(2017,32);   -- '2017-02-01'  
SELECT MAKETIME(19,52,35);  -- '19:52:35'  
-- 日期时间格式化  
SELECT DATE_FORMAT('2017-05-12 17:03:51', '%Y年%m月%d日 %H时%i分%s秒');-- 2017年05月12日 17时03分51秒(具体需要什么格式的数据根据实际情况来;小写h为12小时制;)  
SELECT TIME_FORMAT('2017-05-12 17:03:51', '%Y年%m月%d日 %H时%i分%s秒');-- 0000年00月00日 17时03分51秒(time_format()只能用于时间的格式化)  
-- STR_TO_DATE()和DATE_FORMATE()为互逆操作  

-- MySQL Str to Date (字符串转换为日期)函数:str_to_date(str, format)  
  
SELECT STR_TO_DATE('06.05.2017 19:40:30', '%m.%d.%Y %H:%i:%s');-- 2017-06-05 19:40:30  
SELECT STR_TO_DATE('06/05/2017', '%m/%d/%Y');                  -- 2017-06-05  
SELECT STR_TO_DATE('2017/12/3','%Y/%m/%d')             -- 2017-12-03  
SELECT STR_TO_DATE('20:09:30', '%h:%i:%s')             -- NULL(超过12时的小时用小写h,得到的结果为NULL) 

-- 经特殊日期测试,DATE_SUB(date,INTERVAL expr type)可放心使用  
SELECT DATE_SUB(CURDATE(),INTERVAL 1 DAY);-- 前一天:2017-05-11  
SELECT DATE_SUB(CURDATE(),INTERVAL -1 DAY);-- 后一天:2017-05-13  
SELECT DATE_SUB(CURDATE(),INTERVAL 1 MONTH);-- 一个月前日期:2017-04-12  
SELECT DATE_SUB(CURDATE(),INTERVAL -1 MONTH);-- 一个月后日期:2017-06-12  
SELECT DATE_SUB(CURDATE(),INTERVAL 1 YEAR);-- 一年前日期:2016-05-12  
SELECT DATE_SUB(CURDATE(),INTERVAL -1 YEAR);-- 一年后日期:20178-06-12  
-- MySQL date_sub() 日期时间函数 和 date_add() 用法一致,并且可以用INTERNAL -1 xxx的形式互换使用;  
-- 另外,MySQL 中还有两个函数 subdate(), subtime(),建议,用 date_sub() 来替代。  

-- DATE_ADD(date,INTERVAL expr type) 从日期加上指定的时间间隔  
-- type参数可参考:http://www.w3school.com.cn/sql/func_date_sub.asp  
SELECT DATE_ADD('2017-05-15 10:37:14.123456',INTERVAL 1 YEAR);-- 表示:2018-05-15 10:37:14.123456  
SELECT DATE_ADD('2017-05-15 10:37:14.123456',INTERVAL 1 QUARTER);-- 表示:2017-08-15 10:37:14.123456  
SELECT DATE_ADD('2017-05-15 10:37:14.123456',INTERVAL 1 MONTH);-- 表示:2017-06-15 10:37:14.123456  
SELECT DATE_ADD('2017-05-15 10:37:14.123456',INTERVAL 1 WEEK);-- 表示:2017-05-22 10:37:14.123456  
SELECT DATE_ADD('2017-05-15 10:37:14.123456',INTERVAL 1 DAY);-- 表示:2017-05-16 10:37:14.123456  
SELECT DATE_ADD('2017-05-15 10:37:14.123456',INTERVAL 1 HOUR);-- 表示:2017-05-15 11:37:14.123456  
SELECT DATE_ADD('2017-05-15 10:37:14.123456',INTERVAL 1 MINUTE);-- 表示:2017-05-15 10:38:14.123456  
SELECT DATE_ADD('2017-05-15 10:37:14.123456',INTERVAL 1 SECOND);-- 表示:2017-05-15 10:37:15.123456  
SELECT DATE_ADD('2017-05-15 10:37:14.123456',INTERVAL 1 MICROSECOND);-- 表示:2017-05-15 10:37:14.123457

SELECT DAYNAME('2017-05-15 10:37:14.123456');-- Monday(返回英文星期)  
SELECT MONTHNAME('2017-05-15 10:37:14.123456');-- May(返回英文月份)  
SELECT LAST_DAY('2016-02-01');-- 2016-02-29 (返回月份中最后一天)  
SELECT LAST_DAY('2016-05-01');-- 2016-05-31  


-- MySQL 日期时间 Extract(选取) 函数  
SET @dt = '2017-05-15 10:37:14.123456';  
SELECT DATE(@dt);-- 获取日期:2017-05-15  
SELECT TIME('2017-05-15 10:37:14.123456');-- 获取时间:10:37:14.123456  
SELECT YEAR('2017-05-15 10:37:14.123456');-- 获取年份  
SELECT MONTH('2017-05-15 10:37:14.123456');-- 获取月份  
SELECT DAY('2017-05-15 10:37:14.123456');-- 获取日  
SELECT HOUR('2017-05-15 10:37:14.123456');-- 获取时  
SELECT MINUTE('2017-05-15 10:37:14.123456');-- 获取分  
SELECT SECOND('2017-05-15 10:37:14.123456');-- 获取秒  
SELECT MICROSECOND('2017-05-15 10:37:14.123456');-- 获取毫秒  
SELECT QUARTER('2017-05-15 10:37:14.123456');-- 获取季度  
SELECT WEEK('2017-05-15 10:37:14.123456');-- 20 (获取周)  
SELECT WEEK('2017-05-15 10:37:14.123456', 7);-- ****** 测试此函数在MySQL5.6下无效  
SELECT WEEKOFYEAR('2017-05-15 10:37:14.123456');-- 同week()  
SELECT DAYOFYEAR('2017-05-15 10:37:14.123456');-- 135 (日期在年度中第几天)  
SELECT DAYOFMONTH('2017-05-15 10:37:14.123456');-- 5 (日期在月度中第几天)  
SELECT DAYOFWEEK('2017-05-15 10:37:14.123456');-- 2 (日期在周中第几天;周日为第一天)  
SELECT WEEKDAY('2017-05-15 10:37:14.123456');-- 0  
SELECT WEEKDAY('2017-05-21 10:37:14.123456');-- 6(与dayofweek()都表示日期在周的第几天,只是参考标准不同,weekday()周一为第0天,周日为第6天)  
SELECT YEARWEEK('2017-05-15 10:37:14.123456');-- 201720(年和周)  

SELECT CURDATE();-- 当前日期:2017-05-12  
SELECT CURRENT_DATE();-- 当前日期:等同于 CURDATE()  
SELECT CURRENT_DATE;-- 当前日期:等同于 CURDATE()  
  
SELECT CURTIME();-- 当前时间:11:42:47  
SELECT CURRENT_TIME();-- 当前时间:等同于 CURTIME()  
SELECT CURRENT_TIME;-- 当前时间:等同于 CURTIME()  
-- 那么MySQL中就不用DUAL了吧。  
SELECT NOW();-- 当前日期时间:2017-05-12 11:41:55  
-- 除了 now() 函数能获得当前的日期时间外,MySQL 中还有下面的函数:  
SELECT CURRENT_TIMESTAMP();-- 2017-05-15 10:19:31  
SELECT CURRENT_TIMESTAMP;-- 2017-05-15 10:19:51  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325475476&siteId=291194637