2015-02-09 130 views
1

我有一個棘手的問題(至少對我來說這是棘手的)問題,我想按評論數量安排數據。我的第一個表被稱爲all_comments具有這些列(更多,但不是必需的):SQL從2個表中獲取數據

comment, target_id 

我的第二個表稱爲our_videos具有這些列(更多,但不是必需的):

id, title 

我想得到第二張表上所有target_id與id相同的評論數並按評論數排列該數據。下面是例子我想:

表1:

id target_id 
---------------- 
1  3 
2  5 
3  5 
4  3 
5  3 

表#2:

id title 
----------- 
1 "test" 
2 "another-test" 
3 "testing" 
5 "......" 

這基本上是說數據,即在第二數據庫,並有ID 3有3條評論,並且具有ID 5有2個評論的數據,我想安排本評論計數數據,並得到結果是這樣的:

結果:

id title 
---------------- 
3  "testing" 
5  "......." 
1  "test" 
2  "another-test" 

如果我錯過了只問需要這個問題的任何重要信息,感謝您的幫助,和平:)

+0

在你的查詢中使用join和order語句 – user3479671 2015-02-09 20:08:51

+0

是的,我知道,但它很混亂,試圖找出一種方式,但沒有管理。 – dnc123 2015-02-09 20:09:43

+0

@ dnc123 - 所以嘗試一下...這是一個基本的SELECT語句...你不能用SELECT來傷害任何東西......所以看看SELECT的各個部分並將其放在一起。你有1)選擇... 2)從...和3)在哪裏.... – Ditto 2015-02-09 20:10:59

回答

2

它是非常簡單的查詢,你一定要看看任何SQL教程

天真變種會:

select videos.id, videos.title, count(*) as comment_count 
from videos 
left outer join 
comments 
on (videos.id = comments.target_id) 
group by videos.id, videos.title 
order by comment_count desc 

這個版本有一些性能問題,因爲你必須按名稱,加快它我們通常做下一件事:

select videos.id, videos.title, q.cnt as comment_count 
from videos 
left outer join 
(
    select target_id, count(*) 
    from comments 
    group by target_id 
) as q 
on videos.id = q.target_id 
order by q.cnt DESC 
+0

只需在第一個查詢中使用'max(title)'就可以消除該列上的分組。當然,你需要別名內部計數列。 – shawnt00 2015-02-09 20:31:10

+0

@ shawnt00它會工作,但:1.它會引入額外的字符串比較2.它看起來很奇怪 - 從用戶的角度來看,最大標題是什麼意思? – 2015-02-09 20:32:17

+0

當您知道只有一個值返回時,這是一種平坦化列聚合的常用方法。我認爲這比加入一羣人更好。不知道字符串比較是什麼意思。 – shawnt00 2015-02-09 20:34:51

0
select videos.id, videos.title, isnull(cnt, 0) as cnt 
from videos 
left outer join 
    (select target_id, count(*) as cnt 
    from comments 
    group by target_id) as cnts 
on videos.id = cnts.target_Id 
order by isnull(cnt, 0) desc, videos.title 
0

即使排序不是嚴格地假定在未包含在輸出中的列上發生,也會有一些系統允許您編寫它。我不一定會推薦它,但我可能會認爲這是最直接的。

select id, title from videos 
order by (select count(*) from comments where target_id = videos.id) desc, title 

如果你不介意它在輸出這是一個快速變化:

select id, title from videos, 
    (select count(*) from comments where target_id = videos.id) as comment_count 
order by comment_count desc, title 

SQL通常有很多的選擇。