json據說是MySQL5.7新增數據類型,以下為學習筆記
1)創建使用json數據類型的表:
CREATE TABLE oper_log (
id INT NOT NULL AUTO_INCREMENT,
oper_name VARCHAR(30) NOT NULL,
oper_detail JSON DEFAULT NULL,#注意字段類型為json
PRIMARY KEY(id)
);
2)插入數據
-- 插入含有json數組的記錄
INSERT INTO oper_log(oper_name,oper_detail ) VALUES( 'admin', JSON_ARRAY(1, "course", NULL, TRUE, CURTIME()));
-- 插入含有json對象的記錄
-- 可以使JSON_OBJECT()方法來創建json對象,方法內帶有偶數個參數,一個鍵一個值得形式轉換為json
INSERT INTO oper_log(oper_name,oper_detail ) VALUES( 'admin', JSON_OBJECT("course", "維修保養課程", "currentTime", now()));
-- 如果如下面向JSON_OBJECT()方法傳入奇數個參數,會報錯:Incorrect parameter count in the call to native function 'JSON_OBJECT'
INSERT INTO oper_log(oper_name,oper_detail ) VALUES( 'admin', JSON_OBJECT("course", "維修保養課程", "currentTime"));//錯誤的
-- 還可以使用json字符串的形式傳入json對象
INSERT INTO oper_log(oper_name,oper_detail ) VALUES( 'admin', '{"course":"數據結構課程", "currentTime":"2018-010-1 14:01:00"}');
-- 一定要轉換為字符串,如下直接傳入對象,會報錯:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"course":"數據結構課程", "currentTime":"2018-010-1 14:01:00"})' at line 1
INSERT INTO oper_log(oper_name,oper_detail ) VALUES( 'admin', {"course":"數據結構課程", "currentTime":"2018-010-1 14:01:00"}); //錯誤的
上面插入的數據:
3)查詢json中某個字段的值
SELECT id,JSON_EXTRACT(oper_detail,'$.course') as course FROM oper_log;
或:
SELECT id,oper_detail->'$.course' as course FROM oper_log;
4)以json中的某個字段進行查詢
SELECT * FROM oper_log WHERE JSON_EXTRACT(oper_detail,'$.course') LIKE '%2%';