将属性表作为列和值连接?

时间:2014-07-20 07:41:14

标签: mysql sql postgresql join

CREATE TABLE person_properties (
  person_id INT,  
  key TEXT,
  value TEXT,
  PRIMARY KEY (person_id, key)
);

CREATE TABLE persons (
  id SERIAL PRIMARY KEY
);

我已经这样做了:

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')

我想选择person作为列ageweight作为列,person_properties(或NULL如果是{{1}}不存在)。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

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'

答案 1 :(得分:-1)

您的架构错误。

key已保留&你不能在一个唯一的表中拥有2个主键。

CREATE TABLE person_properties (
  person_id INT,  
  cle TEXT,
  value TEXT,
  PRIMARY KEY (person_id)
);

CREATE TABLE persons (
  id SERIAL 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');

如果你必须有2行同一个键,那就不好了。

我建议你重做//重新考虑你的架构。

编辑:

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');