有没有办法实现这个目标?一个查询,可以从另一个表中的字段获取表名,并将该表的所有列压缩为一行键: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;
答案 0 :(得分:0)
为什么不尝试创建唯一的单个表?
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)
确保您获得所选功能中任何键的唯一值