-1

我正在尝试在我的网站中创建一个下拉列表,显示可用主题的列表,但是每个主题都与所属的标题列表链接,如何使用 sql 查询显示与该主题相关的可用标题的数量.

这是我的表的结构:

主题表

TopicId (int) , TopicTitle (varchar 50)

标题表

TitleId (int), Title (varchar 50), TopicId

下拉列表的结构例如:

体育 10

教育 4

...

4

3 回答 3

3

You can use that query to get the information you need:

SELECT To.TopicTitle, COUNT(Ti.TitleId) as TopicCount
FROM Topics To
INNER JOIN Titles Ti ON To.TopicId = Ti.TitleId
GROUP BY To.TopicId, To.TopicTitle
于 2013-10-14T09:05:41.730 回答
2

It is a basic COUNT query on the Titles table in join with the Topics table

SELECT t.TopicTitle as Topic, Count(tt.TopicID) as TitlesForTopic
FROM Titles tt INNER JOIN Topics t
ON tt.TopicID = t.TopicID
GROUP BY tt.TopicID, t.TopicTitle
ORDER BY COUNT(tt.TopicID) DESC

From C# is basically

string cmdText = "...the above query ....";
using(SqlConnection cn = new SqlConnection(....))
using(SqlCommand cmd = new SqlCommand(cmdText, cn))
using(SqlDataAdapter da = new SqlDataAdapter(cmd))
{
    cn.Open();
    DataTable dt = new DataTable();
    da.Fill(dt);
    gridView.DataSource = dt;
    gridView.DataBind();
}
于 2013-10-14T09:05:04.397 回答
0
SELECT TopicTitle, tt.Count
from Topics t inner join 
   (select count(*) as Count, TopicId 
     from Titles group by TopicId) tt
on t.TopicId = tt.TopicId
于 2013-10-14T09:05:13.293 回答