第三章:USING MySQL(Advanced
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;
MySQL provides many functions to deal with JSON data. Let’s look into the most used ones.
SELECT emp_no, JSON_PRETTY(details) FROM emp_details \G
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;
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','兴江街道');
JSON_REMOVE removes data from a JSON document.
UPDATE emp_details SET
details=JSON_REMOVE(details, "$.address.line2") WHERE
emp_no = 1;
还有window functions 和Generated columns 还未记录 都是很有用的功能
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