[英]Joining a table of properties as columns and values?
CREATE TABLE person_properties (
person_id INT,
key TEXT,
value TEXT,
PRIMARY KEY (person_id, key)
);
CREATE TABLE persons (
id SERIAL PRIMARY KEY
);
I've done this: 我已经做到了:
INSERT INTO persons DEFAULT_VALUES; -- suppose id is 1
INSERT INTO person_properties (person_id, key, value) VALUES (1, 'age', '30')
INSERT INTO person_properties (person_id, key, value) VALUES (1, 'weight', '20lb')
I'd like to select person
s with age
and weight
as columns, with the values from person_properties
(or NULL
if it doesn't exist). 我想选择
person
s的age
和weight
为列,从值person_properties
(或NULL
,如果不存在的话)。 How can I do this? 我怎样才能做到这一点?
SELECT * FROM persons
LEFT OUTER JOIN person_properties p1 ON persons.person_id = p1.person_id AND p1.key = 'age'
LEFT OUTER JOIN person_properties p2 ON persons.person_id = p2.person_id AND p2.key = 'weight'
Your schema is wrong. 您的架构是错误的。
key
is reserved & you can't have 2 primary keys in a unique table. key
是保留键,并且唯一表中不能有2个主键。
CREATE TABLE person_properties (
person_id INT,
cle TEXT,
value TEXT,
PRIMARY KEY (person_id)
);
CREATE TABLE persons (
id SERIAL PRIMARY KEY
);
and 和
You can't to have twice same primary key ... 您不能拥有两次相同的主键...
INSERT INTO person_properties (person_id, cle, value) VALUES (**1**, 'age', '30');
INSERT INTO person_properties (person_id, cle, value) VALUES (**1**, 'weight', '20lb');
If you must have 2 lines with the same key, it's not good. 如果必须有两行具有相同的键,那就不好了。
I advice you to redo//rethink your schema. 我建议您重做//重新考虑您的架构。
EDIT : 编辑:
CREATE TABLE person_properties (
person_id INT NOT NULL AUTO_INCREMENT,
pkey VARCHAR(10),
value TEXT,
PRIMARY KEY (person_id, pkey)
);
CREATE TABLE persons (
id SERIAL PRIMARY KEY
);
INSERT INTO person_properties (pkey, value) VALUES ('age', '30');
INSERT INTO person_properties (pkey, value) VALUES ('weight', '20lb');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.