SQL Counter and returner, doubles the result

只愿长相守 提交于 2019-12-07 11:02:34

问题


I'm trying to make a list, showing all of my Categories on my Forum. Showing the Category name, with an ID, aswell as a count, counting how many Threads is attached to this Category.

It works perfectly, however, it prints the results twice.

This is the 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

Here is the result

And as you can see, it prints the same thing twice, which it should't.

EDIT: Here is the 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>

回答1:


Basically you have 2 places to duplicate rows if your ASP is correct:

1) SQL is wrong (Probably you have to use DISTINCT operator)

2) C# code is wrong (Probably you have to check your data source)

Check your SQL pls. And share your C# code with us.

Use this

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



回答2:


Use Distinct .its remove all duplicated rows

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


来源:https://stackoverflow.com/questions/15247918/sql-counter-and-returner-doubles-the-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!