2013-12-24 83 views
0

我通常不會要求「腳本」,但對於機制,但我認爲在這種情況下,如果我會看到一個例子,我會理解校長。如何在單個查詢中獲取多個列+數?

我有三個表,如下圖所示:

enter image description here

,我想從三個拿到列,加發作的次數在每個系列,並獲得這樣的結果的數:

enter image description here

目前,我打開多個DB線程,恐怕我得到我的網站上更多的訪問者,最終會真正響應緩慢。

任何想法?

非常感謝!

回答

2

首先加入所有的表連接在一起以獲得列。然後,爲了得到一個數,使用窗口函數:

SELECT count(*) over (partition by seriesID) as NumEpisodesInSeries, 
     st.SeriesId, st.SeriesName, et.episodeID, et.episodeName, 
     ct.createdID, ct.CreatorName 
FROM series_table st join 
    episode_table et 
    ON et.ofSeries = st.seriesID join 
    creator_table ct 
    ON ct.creatorID = st.byCreator; 
+0

這是一個很好的答案,我沒有選擇它,因爲第一個答案也是正確的。 –

+0

@MichaelSeltenreich。 。 。這是做你想做的事的正確和最有效的方式。 –

2

試試這個:

http://www.sqlfiddle.com/#!3/5f938/17

select min(ec.num) as NumEpisodes,s.Id,S.Name, 
     Ep.ID as EpisodeID,Ep.name as EpisodeName, 
     C.ID as CreatorID,C.Name as CreatorName 
from Episodes ep 
join Series s on s.Id=ep.SeriesID 
join Creators c on c.Id=s.CreatorID 
join (select seriesId,count(*) as Num from Episodes 
     group by seriesId) ec on s.id=ec.seriesID 
group by s.Id,S.Name,Ep.ID,Ep.name,C.ID,C.Name 

感謝戈登

+0

讓我們來看看。 。 。你正在通過'episodeID'聚合並期望'count(distinct episodeId)'返回一個非0或1的值? –

+0

非常感謝! –

1

我會做到以下幾點:

SELECT (SELECT Count(*) 
     FROM episodetbl e1 
     WHERE e1.ofseries = s.seriesid) AS "#ofEpisodesInSeries", 
     s.seriesid, 
     s.seriesname, 
     e.episodeid, 
     e.episodename, 
     c.creatorid, 
     c.creatorname 
FROM seriestbl s 
     INNER JOIN creatortbl c 
       ON s.bycreator = c.creatorid 
     INNER JOIN episodetbl e 
       ON e.ofseries = s.seriesid 
2

做你的適當的表和它們的ID之間加入你所期望的,並且還加入到使用Episodes表確定總髮作次數的子查詢的結果。

SELECT SeriesCount.NumEpisodes AS #OfEpisodesInSeries, 
    S.id AS SeriesId, 
    S.name AS SeriesName, 
    E.id AS EpisodeId, 
    E.name AS EpisodeName, 
    C.id AS CreatorId, 
    C.name AS CreatorName 
FROM 
Series S 
INNER JOIN 
Episodes E 
ON E.seriesId = S.id 
INNER JOIN 
Creators C 
ON S.creatorId = C.id 
INNER JOIN 
(
    SELECT seriesId, COUNT(id) AS NumEpisodes 
    FROM Episodes 
    GROUP BY seriesId 
) SeriesCount 
ON SeriesCount.seriesId = S.id 

SQL Fiddle模式:

CREATE TABLE Series (id int, name varchar(20), creatorId int) 

INSERT INTO Series VALUES(1, 'Friends', 1) 
INSERT INTO Series VALUES(2, 'Family Guy', 2) 
INSERT INTO Series VALUES(3, 'The Tonight Show', 1) 

CREATE TABLE Episodes (id int, name varchar(20), seriesId int) 

INSERT INTO Episodes VALUES(1, 'Joey', 1) 
INSERT INTO Episodes VALUES(2, 'Ross', 1) 
INSERT INTO Episodes VALUES(3, 'Phoebe', 1) 
INSERT INTO Episodes VALUES(4, 'Stewie', 2) 
INSERT INTO Episodes VALUES(5, 'Kevin Kostner', 3) 
INSERT INTO Episodes VALUES(6, 'Brad Pitt', 3) 
INSERT INTO Episodes VALUES(7, 'Tom Hanks', 3) 
INSERT INTO Episodes VALUES(8, 'Morgan Freeman', 3) 

CREATE TABLE Creators (id int, name varchar(20)) 

INSERT INTO Creators VALUES(1, 'Some Guy') 
INSERT INTO Creators VALUES(2, 'Seth McFarlane') 
相關問題