根据这个JSON Insert into a MySQL table or update if exists,我得到了回答mysql来插入/更新下面的json。
"google",
"20180510",
"{
"gmail_page_viewed" : 12000300,
"search_page_viewed" : 9898884726423
}"
进入SCHEMA
CREATE TABLE TAG_COUNTER (
account varchar(36) NOT NULL,
time_id INT NOT NULL,
counters JSON,
PRIMARY KEY (account, time_id)
)
如下所示
INSERT INTO `TAG_COUNTER`
(`account`, `time_id`, `counters`)
VALUES
('google', '20180510', '{"gmail_page_viewed": 1, "search_page_viewed": 1}'),
('google', '20180510', '{"gmail_page_viewed": 1, "search_page_viewed": 1}'),
('google', '20180511', '{"gmail_page_viewed": 1, "search_page_viewed": 1}'),
('google', '20180511', '{"gmail_page_viewed": 1, "search_page_viewed": 1}'),
('google', '20180512', '{"gmail_page_viewed": 1, "search_page_viewed": 1}')
ON DUPLICATE KEY UPDATE `counters` =
JSON_SET(`counters`,
'$."gmail_page_viewed"',
IFNULL(`counters` ->> '$."gmail_page_viewed"', 0) + 1,
'$."search_page_viewed"',
IFNULL(`counters` ->> '$."search_page_viewed"', 0) + 1
);
然而,使用group by很难从中检索数据,因为json键是动态的而不是静态的。
因此,如果我将json更改为具有以下格式的静态密钥(例如page_name,page_visits),则可以轻松进行检索(groupby / orderby)。
"google",
"20180510",
'{
"gmail_page_viewed" : {"page_name" : "gmail_page_viewed", "page_visits" : 12000300},
"search_page_viewed" : {"page_name" : "search_page_viewed", "page_visits" : 12000300}
}"
但我无法弄清楚如何准备INSERT ON DUPLICATE KEY UPDATE
查询。我已经尝试了6个多小时,但没有运气,数据插入不正确,或者没有正确更新访问次数。有时引用会被添加到内容中。
有人可以帮我吗?