我有如下架构:
CREATE TABLE prop_set (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name varchar(255),
PRIMARY KEY (id)
);
CREATE TABLE users_props (
user_id int UNSIGNED NOT NULL,
prop_id int UNSIGNED NOT NULL,
value text,
PRIMARY KEY (user_id,prop_id)
);
CREATE TABLE user (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
name varchar(255),
PRIMARY KEY (id)
);
INSERT INTO prop_set SET name="prop1";
INSERT INTO prop_set SET name="prop2";
INSERT INTO prop_set SET name="prop3";
INSERT INTO user SET name="user1";
INSERT INTO user SET name="user2";
INSERT INTO users_props set user_id=1,prop_id=1,value="prop1 user1";
INSERT INTO users_props set user_id=1,prop_id=2,value="prop2 user1";
INSERT INTO users_props set user_id=1,prop_id=3,value="prop3 user1";
INSERT INTO users_props set user_id=2,prop_id=1,value="prop1 user2";
INSERT INTO users_props set user_id=2,prop_id=2,value="prop2 user2";
INSERT INTO users_props set user_id=2,prop_id=3,value="prop3 user2";
现在我运行如下选择:
SELECT u.name,ps.name AS prop,up.value
FROM USER u
JOIN users_props up ON u.id=up.user_id
JOIN prop_set ps ON ps.id=up.prop_id;
并获得输出:
| NAME | PROP | VALUE |
-------------------------------
| user1 | prop1 | prop1 user1 |
| user2 | prop1 | prop1 user2 |
| user1 | prop2 | prop2 user1 |
| user2 | prop2 | prop2 user2 |
| user1 | prop3 | prop3 user1 |
| user2 | prop3 | prop3 user2 |
小提琴 有没有办法让mysql返回以下输出?
| NAME | prop1 | prop2 | prop3 |
---------------------------------------------------
| user1 | prop1 user1 | prop2 user1 | prop3 user1 |
| user2 | prop1 user2 | prop2 user2 | prop3 user2 |
我正在寻找 mysql - 唯一的解决方案。