0

我有这个表:

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;

我想问一下,是否有可能创建一种类型view,其中包含table1中提到的两个用户(来自)的名称table2?谢谢你的帮助。

4

2 回答 2

1

试试这个:

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;
于 2013-02-08T10:30:12.097 回答
0

这会将所有名称放在视图中,其 id 都存在于 Table2 中的两列中。

CREATE VIEW MyView AS SELECT DISTINCT Name FROM Table1 
WHERE Id IN (SELECT DISTINCT Id1 FROM Table2 
UNION SELECT DISTINCT Id2 FROM Table2)
于 2013-02-08T10:27:38.823 回答