Mysql创建一个链接两个表的视图

时间:2017-12-17 05:59:30

标签: mysql view

我有两个由UID链接的表

table A
1 A1
2 B3
3 E9
4 F2

table B
1 2
2 4
3 1

我想基于表B创建一个视图,其中包含A&#39的UID。

View_link
1 2 A1 B3
2 4 B3 F2
3 1 E9 A1

我尝试过的观点如下。

ALTER VIEW  view_links AS 
SELECT 
    tableB.source as sourceID,
    tableB.target as targetID,
    tabelA.UID as sourceUID
FROM tableA, tableB 
where tableB.source=tableA.id

如何将targetUID添加到视图中?

1 个答案:

答案 0 :(得分:0)

抓取子查询中的链接并加入表a(并且不使用隐式连接)

例如

drop table if exists ta,tb;
create table ta(id int, uid varchar(2));
create table tb(id int, uid varchar(2));

insert into ta values
(1, 'A1'),
(2, 'B3'),
(3, 'E9'),
(4, 'F2');

insert into tb values
(1 ,2),
(2 ,4),
(3 ,1);

select taid,tbuid,tauid,ta.uid 
from
(
select ta.id taid,ta.uid tauid,tb.uid tbuid
from ta
join tb on tb.id = ta.id
) a
join ta on ta.id = tbuid
order by taid

结果

+------+-------+-------+------+
| taid | tbuid | tauid | uid  |
+------+-------+-------+------+
|    1 | 2     | A1    | B3   |
|    2 | 4     | B3    | F2   |
|    3 | 1     | E9    | A1   |
+------+-------+-------+------+
3 rows in set (0.00 sec)