SQL C#过滤类似记录

时间:2015-01-03 16:48:55

标签: c# sql asp.net sql-server-express

问题与我之前提出的问题有关,但我需要一点帮助......

我有一张兴趣表,其中存储了SeekersEmployers ...

的兴趣

兴趣表就像:

int_id   FK_is_ID  FK_ie_ID  FK_ic_ID
-------------------------------------
1           2          null      3
2           2          null      5
3           null       1         3
4           null       3         1
5           null       2         5
6           4          null      1
6           3          1         2

FK_is_id = Seeker ID
FK_ie_id = Employer ID
FK_ic_id = Category ID

因此,当搜索者登录时,我正在尝试检索与登录的搜索者具有相似兴趣的EMPLOYER名称...

我有一个工作正常的代码,给我想要的输出..

SqlConnection myConn2;
SqlCommand myCommand2;
SqlDataReader myReader2;
String SQL2, divjobs;

myConn2 = new SqlConnection(WebConfigurationManager.ConnectionStrings["ApplicationServices"].ToString());
divjobs = "<ul>";
myConn2.Open();
SQL2 = "SELECT ins.int_id, ins.FK_is_ID, ine.FK_ie_ID,emp.e_name,ine.int_id FROM  Interests ins INNER JOIN Interests ine ON ins.FK_ic_ID = ine.FK_ic_ID FULL OUTER JOIN employers emp ON emp.e_id=ine.FK_ie_id WHERE  ins.FK_is_ID = @sid  AND ine.FK_ie_ID IS NOT null order by emp.e_name ASC";

myCommand2 = new SqlCommand(SQL2, myConn2);
myCommand2.Parameters.AddWithValue("@sid", ssid);

myReader2 = myCommand2.ExecuteReader();

if (myReader2.HasRows)
{
    while (myReader2.Read())
    {
        divjobs = divjobs + "<li>" + "<a href='../employers/viewemployer.aspx?EID=" + myReader2["FK_ie_id"] + "'>" + "<div class='jtitle'>" + myReader2["e_name"] + "</div>" + "</li>";
    }
    divjobs = divjobs + "</ul>";
    joblist.InnerHtml = divjobs;
}
else
{
    joblist.InnerHtml = "<div style='font-weight:bold;padding:20px;font-size:1.2em;background-color:white;'>"+ "Looks like there is nothing to load!" + "</div>";
}

myConn2.Close();

唯一的问题是如果雇主有2个利益,那么输出会给雇主姓名两次!我希望它只来一次......!

无论如何都要这样做,任何帮助都会受到赞赏......?

1 个答案:

答案 0 :(得分:1)

目前,您的结果处于“兴趣”级别,但您确实希望它在雇主级别 - 以下将返回具有匹配兴趣的雇主的明确列表 - 我还抛出了匹配的聚合(计数)每个人的利益:

SELECT
    ins.FK_ie_ID,
    emp.e_name,
    COUNT(ins.int_id) AS InterestCount
FROM
Interests ins 
INNER JOIN 
Interests ine 
    ON ins.FK_ic_ID = ine.FK_ic_ID 
INNER JOIN 
employers emp 
    ON emp.e_id = ine.FK_ie_id 
WHERE  
    ins.FK_is_ID = @sid  
GROUP BY 
    ins.FK_ie_ID,
    emp.e_name
order by emp.e_name ASC

我希望我能正确理解你想要的东西。

此外,我发现您的列命名非常难以使用。由于这个原因,查询中很可能存在拼写错误。他们有这么神秘的原因吗?或者,他们是否不受你的控制?