mysql8学习手册第三章mysql高级使用

第三章:USING MySQL(Advanced

  • Using JSON
  • Common table expressions (CTE)
  • Generated columns
  • Window function

Suppose you want to store more details about your employees; you can save them using JSON:

CREATE TABLE emp_details(
emp_no int primary key,
details json
);
INSERT INTO emp_details(emp_no, details)
VALUES ('1',
'{ "location": "IN", "phone": "+11800000000",
"email": "[email protected]", "address": { "line1":
"abc", "line2": "xyz street", "city": "Bangalore",
"pin": "560103"} }'
);

You can retrieve the fields of the JSON column using the -> and ->> operators:

select * from emp_details;
SELECT emp_no, details->'$.address.pin' pin FROM emp_details;

SELECT emp_no, details->>'$.address.pin' pin FROM emp_details;

select emp_no,details->>'$.phone' from emp_details;

JSON functions

MySQL provides many functions to deal with JSON data. Let’s look into the most used ones.

  • Pretty view
    To display JSON values in pretty format, use the JSON_PRETTY() function:

SELECT emp_no, JSON_PRETTY(details) FROM emp_details \G

  • Searching
SELECT emp_no FROM emp_details WHERE details->>'$.address.pin'="560103";

SELECT JSON_CONTAINS(details->>'$.address.pin', "560103") FROM emp_details;


How to search for a key? Suppose you want to check whether address.line1 exists or not:

SELECT JSON_CONTAINS_PATH(details, 'one',"$.address.line1") FROM emp_details;

SELECT JSON_CONTAINS_PATH(details, 'all',"$.address.line1") FROM emp_details;
  • Modifying
    You can modify the data using three different functions: JSON_SET() , JSON_INSERT() , JSON_REPLACE() . Before MySQL 8, we needed a full update of the entire column, which is not the optimal way:
UPDATE
    emp_details
SET
    details = JSON_SET(details, "$.address.pin",
"560100", "$.nickname", "kai")
WHERE
    emp_no = 1;
update emp_details set
details=JSON_SET(
details,'$.phone','18725883714',
'$.address.line2','兴江街道');
update emp_details set
details=JSON_INSERT(
details,'$.phone','154077',
'$.address.line2','兴江街道');
update emp_details set
details=JSON_REPLACE(
details,'$.phone','104',
'$.address.line2','兴江街道');
  • Removing

JSON_REMOVE removes data from a JSON document.

UPDATE emp_details SET
details=JSON_REMOVE(details, "$.address.line2") WHERE
emp_no = 1;

Common table expressions (CTE)

还有window functions 和Generated columns 还未记录 都是很有用的功能

MySql按天,日,小时,分钟分组数据

mysql按 时间 分组数据
如果按小时分组 则 格式调整为 “%Y-%m-%d %H:00:00” 
按分钟分组 则 格式调整为 “%Y-%m-%d %H:%i:00”

SELECT 
COUNT(*), 
DATE_FORMAT(time ,'%Y-%m-%d %H:00:00') as time 
FROM 
tableName 
GROUP BY time 

参考:http://www.w3school.com.cn/sql/func_date_format.asp

你可能感兴趣的:(数据库)