0

有没有办法做到这一点?一个查询,可以从另一个表的一个字段中获取一个表名,并将该表的所有列压缩为一行 key:val; 一对。(从关联表 ft_data_id 中只会确定一个)

小提琴:http ://sqlfiddle.com/#!2/b0c27

ID  FT_ID   FT_DATA_ID  NAME        TABLE                   DATA
1   1       1           one         features_data_one       ro_one: A; ro_two: B
2   2       1           two         features_data_two       rt_two: C; rt_two: D



/****** list of features with the name and the table the data lies in */
CREATE TABLE features (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(20) NOT NULL,
        `table` VARCHAR(255) NOT NULL
);
INSERT INTO features(name, `table`) VALUES ('one', 'features_data_one');
INSERT INTO features(name, `table`) VALUES ('two', 'features_data_two');


/****** feature one */
CREATE TABLE features_data_one (
        id INT AUTO_INCREMENT PRIMARY KEY,
        ro_one VARCHAR(20) NOT NULL,
        ro_two VARCHAR(20) NOT NULL
);
INSERT INTO features_data_one (ro_one, ro_two) VALUES ('A', 'B');



/****** feature two */
CREATE TABLE features_data_two (
        id INT AUTO_INCREMENT PRIMARY KEY,
        rt_one VARCHAR(20) NOT NULL,
        rt_two VARCHAR(20) NOT NULL
);
INSERT INTO features_data_two (rt_one, rt_two) VALUES ('C', 'D');

/****** association table which links a feature with a feature_id. The feature_id is the id in a specific table. This table is specificed in the feature table. */
CREATE TABLE assoc (
        id INT AUTO_INCREMENT PRIMARY KEY,
        ft_id INT NOT NULL,
        ft_data_id INT NOT NULL
);
INSERT INTO assoc (ft_id, ft_data_id) VALUES (1, 1);
INSERT INTO assoc (ft_id, ft_data_id) VALUES (2, 1);


SELECT * 
FROM assoc a
INNER JOIN features as ft ON a.ft_id = ft.id;
4

1 回答 1

0

恕我直言,您正试图对 SQL 做出一些奇怪且非常不自然的事情。

为什么不尝试创建唯一的单表?

CREATE TABLE features_all (
        id INT AUTO_INCREMENT PRIMARY KEY,
        feature_name varchar(20) not null,
        ro_one VARCHAR(20) NOT NULL,
        ro_two VARCHAR(20) NOT NULL,
        index(feature_name)
);
INSERT INTO features_all (feature_name, ro_one, ro_two) values
('one', 'A', '1'),
('one', 'C', '31'),
('one', 'Z', '71'),
('two', 'A', '1'),
('two', 'S', '12'),
('two', 'D', '14');

这种风格有助于填充特征(添加第三个等)。只需插入新行!无需创建表!

我不知道你的情况,但有时更换是有用的

        index(feature_name)

        unique(feature_name, ro_one)

以确保您将获得所选功能中任何键的唯一值

于 2013-04-08T05:56:56.163 回答