使用PFK的MySQL视图
我有以下表格:使用PFK的MySQL视图,mysql,view,Mysql,View,我有以下表格: Create table table1 ( id Int UNSIGNED NOT NULL, name VARCHAR(255) NOT NULL, Primary Key(id), Unique Key `name` (`name`)) ENGINE = InnoDB; Create table table2 ( id1 Int UNSIGNED NOT NULL, id2 Int UNSIGNED NOT NULL, Primary Key (id1,i
Create table table1 (
id Int UNSIGNED NOT NULL,
name VARCHAR(255) NOT NULL,
Primary Key(id),
Unique Key `name` (`name`))
ENGINE = InnoDB;
Create table table2 (
id1 Int UNSIGNED NOT NULL,
id2 Int UNSIGNED NOT NULL,
Primary Key (id1,id2))
ENGINE = InnoDB;
Alter table table2 add Foreign Key (id1) references table1 (id)
on delete restrict on update restrict;
Alter table table2 add Foreign Key (id2) references table1 (id)
on delete restrict on update restrict;
我想问一下,是否有可能创建一种类型的
视图
,其中包含表2
中提到的两个用户的姓名(来自表1
)?感谢您的帮助。这将在视图中放置ID在表2中的两列中的所有名称
CREATE VIEW MyView AS SELECT DISTINCT Name FROM Table1
WHERE Id IN (SELECT DISTINCT Id1 FROM Table2
UNION SELECT DISTINCT Id2 FROM Table2)
试试这个:
CREATE OR REPLACE VIEW ViewName
AS
SELECT
T1.Name Name1, T2.Name Name2
FROM Table2 T
JOIN Table1 T1
ON T.Id1 = T1.Id
JOIN Table1 T2
ON T.Id2 = T2.Id;