我正在尝试在我的网站上创建一个显示可用主题列表的下拉列表,但每个主题都与一个属于的标题列表相关联,如何显示与此主题相关的可用标题数量一个SQL查询。
这是我表格的结构:
主题表
TopicId (int) , TopicTitle (varchar 50)
标题表
TitleId (int), Title (varchar 50), TopicId
以及下拉列表的结构例如:
体育10
教育4
...
答案 0 :(得分:3)
您可以使用该查询来获取所需信息:
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
答案 1 :(得分:2)
这是与主题表
连接时Titles表上的基本COUNT查询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
来自C#基本上是
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();
}
答案 2 :(得分: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