SQL - 创建连接在一起的多个表的视图

时间:2013-06-08 15:31:28

标签: mysql sql

我需要创建一个连接到名为artists的表的多个表的视图,以便可以轻松引用它。

视图中数据的排列是我正在努力的方向。我需要连接的行为彼此独立,因此不会重复数据。我将给出我到目前为止的查询,然后是一些例子;

CREATE VIEW stream_view AS
SELECT
A.ID,
T.T_ID,
T.name AS name,
T.pic AS T_pic,
T.timestamp AS T_ts,
(SELECT COUNT(*) FROM track_plays WHERE T_ID = T.T_ID) AS plays,
(SELECT COUNT(*) FROM track_downloads WHERE T.T_ID) AS downloads,
(SELECT COUNT(*) FROM likes WHERE E_ID = T.ID AND event = 'T') AS T_likes,
S.S_ID,
S.status,
S.timestamp AS S_ts,
(SELECT COUNT(*) FROM likes WHERE E_ID = S.ID AND event = 'S') AS S_likes,
G.G_ID,                                                
G.gig_name,
G.date_time,
G.lineup,
G.price, 
G.currency,
G.pic AS G_pic,
G.ticket,
G.venue,
G.timestamp AS G_ts,
(SELECT COUNT(*) FROM likes WHERE E_ID = G.ID AND event = 'G') AS G_likes

FROM artists A
LEFT JOIN status S 
ON S.ID = A.ID
LEFT JOIN gigs G ON G.ID = A.ID
LEFT JOIN tracks T ON T.ID = A.ID

我将举一些例子,但为了简单起见,只包括所有内容的ID。

应该发生什么的示例

假设我有两个3 A.ID的1,2和3.这些ID中的每一个都有G_ID个,T_IDS_ID属于他们。该视图应该出现,因此没有重复项,每个G_IDT_IDS_ID位于不同的行,并分配给他们的A_ID。像这样的东西;

 A_ID    G_ID    T_ID    S_ID

 1       1       NULL    NULL
 1       NULL    4       NULL
 2       NULL    NULL    5
 3       2       NULL    NULL
 3       NULL    8       NULL
 3       NULL    NULL    8

目前发生的事情示例

 A_ID    G_ID    T_ID    S_ID

 1       1       NULL    NULL
 1       1       4       NULL
 2       NULL    NULL    5
 3       2       NULL    NULL
 3       2       8       NULL
 3       2       8       8

正如您所看到的那样,数据是重复的,因此该表包含多个相同的G_IDT_IDS_ID。这些ID在其自己的列中是唯一的,因此它们不能与G_ID重复,但G_IDT_ID可以具有相同的值。

1 个答案:

答案 0 :(得分:0)

现在,您正在将这些行连接在一起。您似乎想要union all查询。

这是基于您提供的样本数据的结构:

select a.*, t.*
from ((select a_id, g_id, null as t_id, null as s_id
       from gigs g
      ) union all
      (select a_id, null as g_id, t_id, null as s_id
       from tracks t
      ) union all
      (select a_id, null as g_id, null as t_id, s_id
       from status s
      )
     ) t join
     artists a
     on t.a_id = a.a_id