1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
| CREATE TABLE json_demo ( id INT AUTO_INCREMENT PRIMARY KEY, user_id INT NOT NULL, profile JSON COMMENT '用户配置信息', settings JSON COMMENT '用户设置', metadata JSON COMMENT '元数据', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, email VARCHAR(100) AS (JSON_UNQUOTE(JSON_EXTRACT(profile, '$.email'))) STORED, age INT AS (JSON_EXTRACT(profile, '$.age')) VIRTUAL, INDEX idx_email (email), INDEX idx_user_id (user_id) );
INSERT INTO json_demo (user_id, profile, settings, metadata) VALUES (1001, JSON_OBJECT('name', '张三', 'email', 'zhangsan@example.com', 'age', 28, 'city', '北京'), JSON_OBJECT('theme', 'dark', 'language', 'zh-CN', 'notifications', true), JSON_OBJECT('source', 'web', 'device', 'desktop', 'ip', '192.168.1.100') ), (1002, JSON_OBJECT('name', '李四', 'email', 'lisi@example.com', 'age', 32, 'city', '上海', 'hobbies', JSON_ARRAY('reading', 'swimming')), JSON_OBJECT('theme', 'light', 'language', 'en-US', 'notifications', false), JSON_OBJECT('source', 'mobile', 'device', 'iPhone', 'ip', '192.168.1.101') );
SELECT user_id, JSON_EXTRACT(profile, '$.name') as name, JSON_EXTRACT(profile, '$.email') as email, JSON_EXTRACT(profile, '$.age') as age FROM json_demo;
SELECT user_id, JSON_UNQUOTE(JSON_EXTRACT(profile, '$.name')) as name, JSON_UNQUOTE(JSON_EXTRACT(profile, '$.city')) as city FROM json_demo;
SELECT user_id, profile->'$.name' as name_with_quotes, profile->>'$.name' as name_without_quotes, profile->>'$.age' as age FROM json_demo;
SELECT user_id, profile->>'$.name' as name, JSON_EXTRACT(profile, '$.hobbies') as hobbies, JSON_LENGTH(profile, '$.hobbies') as hobbies_count FROM json_demo WHERE JSON_EXTRACT(profile, '$.hobbies') IS NOT NULL;
SELECT * FROM json_demo WHERE profile->>'$.city' = '北京';
SELECT * FROM json_demo WHERE JSON_EXTRACT(settings, '$.theme') = 'dark';
UPDATE json_demo SET profile = JSON_SET(profile, '$.age', 29) WHERE user_id = 1001;
UPDATE json_demo SET profile = JSON_SET(profile, '$.phone', '13800138000') WHERE user_id = 1001;
UPDATE json_demo SET profile = JSON_REMOVE(profile, '$.phone') WHERE user_id = 1001;
SELECT JSON_EXTRACT(settings, '$.theme') as theme, COUNT(*) as user_count FROM json_demo GROUP BY JSON_EXTRACT(settings, '$.theme');
SELECT '使用场景' as 场景, '优点' as 优点, '缺点' as 缺点, '建议' as 建议 UNION ALL SELECT '用户配置', '灵活存储复杂数据', '查询性能相对较低', '为常用字段创建虚拟列和索引' UNION ALL SELECT '产品属性', '适合变化的属性结构', '不支持外键约束', '重要字段建议单独存储' UNION ALL SELECT '日志数据', '便于存储结构化日志', '占用存储空间较大', '定期清理和归档' UNION ALL SELECT '配置信息', '避免频繁修改表结构', '数据一致性检查复杂', '制定JSON结构规范';
|