2013-03-06 77 views
4

我正在嘗試創建一個列表,在論壇上顯示我的所有類別。顯示類別名稱,帶有ID和計數,統計附加到該類別的線程數。SQL計數器和返回者,將結果加倍

它可以很好地工作,但是它會打印兩次結果。

這是SQL

SELECT categories.category_name, threads.thread_category_id, COUNT(*) 
         AS 'threadCount' FROM threads 
         INNER JOIN categories ON categories.category_id = threads.thread_category_id 
         GROUP BY categories.category_name, threads.thread_category_id 

下面是結果 enter image description here

正如你所看到的,它打印同樣的事情兩次,它should't。

編輯:這裏是ASP。

<asp:Repeater ID="categories" runat="server"> 
    <HeaderTemplate> 
    <table id="kategorier" cellspacing="0"> 
     <tr> 
      <td class="head">Name</td> 
      <td class="head" style="width:70px">Number of Threads</td> 
     </tr> 
    </HeaderTemplate> 
    <ItemTemplate> 
     <tr> 
      <td class="item"><a href="Kategori.aspx?id=<%# Eval("thread_category_id") %>"><%# Eval("category_name") %> - ID: <%# Eval("thread_category_id")%></a></td> 
      <td class="item" style="text-align:right"><%# Eval("threadCount") %></td> 
     </tr> 
    </ItemTemplate> 
    <FooterTemplate> 
    </table> 
    </FooterTemplate> 
</asp:Repeater> 
+0

當你在上面直接在MySQL執行該查詢,確實有重新調整的重複行? – 2013-03-06 12:57:41

+0

我不這樣做,當我在查詢運行/構建器上運行它時,它不會重複。 – 2013-03-06 12:59:44

+3

所以問題不在於查詢,而是在asp代碼上。 – 2013-03-06 13:00:14

回答

3

基本上,你有2個地方重複的行,如果你的ASP是正確的:

1)SQL是錯誤的(也許你有使用DISTINCT運算符)

2)C#代碼有誤(可能需要檢查數據源)

檢查你的SQL請求。並與我們分享您的C#代碼。

使用此

SELECT distinct category_name, thread_category_id, threadCount 
FROM 
(SELECT categories.category_name, threads.thread_category_id, COUNT(*) 
         AS 'threadCount' FROM threads 
         INNER JOIN categories ON categories.category_id = threads.thread_category_id 
         GROUP BY categories.category_name, threads.thread_category_id) A 
+0

儘管如此,大部分的答案建議。這不起作用,仍然重複。 – 2013-03-06 13:09:49

+0

@KevinJensenPetersen你可以直接在MS SQL Server Management Studio中執行我的tsql嗎?當你從數據庫獲取數據來查看這些行是否重複時,你也可以調試該行嗎? – 2013-03-06 13:13:46

+1

沒有人注意到,我是一個巨大的白癡,因爲我沒有注意到這一點,我有兩個adapter.Fill(dt);在我的代碼在同一個地方,這導致了重複。對於那個很抱歉! – 2013-03-06 13:18:31

0

使用distinct。其刪除所有重複的行

SELECT DISTINCT(threads.thread_category_id), categories.category_name, COUNT(*) 
         AS 'threadCount' FROM threads 
         INNER JOIN categories ON categories.category_id = threads.thread_category_id 
         GROUP BY threads.thread_category_id 
+0

仍然重複。 – 2013-03-06 13:05:35

+0

現在我編輯了我的post.please再檢查一個 – 2013-03-06 13:14:58

+0

沒關係大家,我是一個巨大的白癡,因爲我沒有注意到這一點,我有兩個adapter.Fill(dt);在我的代碼在同一個地方,這導致了重複。對於那個很抱歉! – 2013-03-06 13:21:40