如何创建可以将字符串数组作为列值保存的表。例如:
CREATE TABLE bug
(
id BIGINT NOT NULL,
title VARCHAR,
description VARCHAR,
timestamp TIMESTAMP,
duedate DATETIME,
assignedto VARCHAR,
userid BIGINT NOT NULL,
viewedby VARCHAR[],
watchers VARCHAR[],
priority VARCHAR,
tags VARCHAR[],
comments VARCHAR[],
PRIMARY KEY(id)
FOREIGN KEY(userid) REFERENCES user(id)
);
在插入数据时如何在此字段中插入值。
答案 0 :(得分:1)
通常情况下,您不会那样做,从而降低了可用性(即无法轻易辨别第n个元素)。
相反,您可以创建一个表,该表的每个元素都有一列,并提供指向各个错误的链接/引用/映射。
例如您可能会有类似以下内容的东西:-
DROP TABLE If EXISTS bug;
DROP TABLE IF EXISTS bugarrayelements;
CREATE TABLE IF NOT EXISTS bug
(
id BIGINT NOT NULL,
title VARCHAR,
description VARCHAR,
timestamp TIMESTAMP,
duedate DATETIME,
assignedto VARCHAR,
userid BIGINT NOT NULL,
viewedby VARCHAR[],
watchers VARCHAR[],
priority VARCHAR,
tags VARCHAR[],
comments VARCHAR[],
PRIMARY KEY(id)
--FOREIGN KEY(userid) REFERENCES user(id) -- commented out for convenience
);
CREATE TABLE IF NOT EXISTS bugarrayelements
(bug_reference INTEGER, element_order INTEGER, element_data TEXT
);
-- First bug with representation of a 5 element string array
INSERT INTO bug (id,title,userid) VALUES(1,'bug001',100);
INSERT INTO bugarrayelements VALUES
(1,1,'This failed.'),
(1,2,'It failed with this error.'),
(1,3,'It failed on line 2450.'),
(1,4,'Out of a total of 9567 lines of code.'),
(1,5,'blah blah blah.')
;
-- Second bug
INSERT INTO bug (id,title,userid) VALUES(2,'bug500',321);
INSERT INTO bugarrayelements VALUES
(2,1,'This failed.'),
(2,2,'It failed with this error.'),
(2,3,'It failed on line 2450'),
(2,4,'Out of a total of 9567 lines of code.'),
(2,5,'blah blah blah.'),
(2,1,'This failed.'),
(2,2,'It failed with this error.'),
(2,3,'It failed on line 2450'),
(2,4,'Out of a total of 9567 lines of code.'),
(2,5,'blah blah blah.')
;
SELECT * FROM bug JOIN bugarrayelements ON bug_reference = bug.id ORDER BY bug.id,element_order;
SELECT bug.title,bug.userid, group_concat(element_data,' ~~~ ') FROM bug JOIN bugarrayelements ON bug_reference = bug.id GROUP BY bug.id ORDER BY bug.id, element_order;
使用以上方法,第一个结果将是:-
第二个结果是:-
上面显示了多个插入(即所有数组元素),它们也可以单独添加(可能在事务中)