简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM