0

我需要创建多个表的视图,这些表连接到一个名为的表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。

应该发生的事情的例子

假设我有两个 3A.ID的 1、2 和 3。这些 ID 中的每一个都有一些属于它们的G_ID'、T_ID' 和'。S_ID视图应该出现,因此没有重复项,并且每个G_IDT_ID或者S_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 在它们自己的列中是唯一的,因此它们不能与 a 重复,G_ID但是 aG_ID和 aT_ID可以具有相同的值。

4

1 回答 1

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
于 2013-06-08T15:36:52.647 回答