如何从3个链接表创建视图,从数据开始到另一个表

时间:2014-06-07 15:42:58

标签: mysql

在我的数据库中我有4个表。

tb_main (id_c)
tb_r (id_r, desc_r)
tb_p (id_p, id_r, desc_p)
tb_c (id_c, id_p, desc_c)

表tb_r通过字段id_r与表tb_p“链接”。

表tb_p通过字段id_p与表tb_c“链接”。

表tb_main的id_c字段与tb_c相同。

我想从tb_main字段id_c

开始创建一个视图(测试)

测试视图应该包含此数据

test ( id_c, desc_c, id_p, desc_p, id_r, desc_r)

我只做了第一步

SELECT  tb_main.id_c,
FROM    tb_main
JOIN tb_c ON tb_main.id_c = tb_c.id_c

有可能吗?我怎么能这样做?谢谢。

2 个答案:

答案 0 :(得分:2)

试试这个(你可以根据你的需要使用内/右/左连接):

SELECT tb_c.id_c AS id_c, desc_c, tb_p.id_p AS id_p, desc_p,
       tb_r.id_r AS id_r, desc_r
FROM tb_c  
INNER JOIN tb_p ON tb_c.id_p = tb_p.id_p
INNER JOIN tb_r ON tb_r.id_r = tb_p.id_r

答案 1 :(得分:1)

如果你想从tb_main开始尝试这个

SELECT tb_c.id_c AS id_c, desc_c, tb_p.id_p AS id_p, desc_p, 
       tb_r.id_r AS id_r, desc_r 
FROM tb_main 
INNER JOIN tb_c  ON tb_main.id_c  = tb_c.id_c  
INNER JOIN tb_p ON tb_c.id_p = tb_p.id_p 
INNER JOIN tb_r ON tb_r.id_r = tb_p.id_r