2013-03-06 17 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