c# - 如何在SQL中使用同一表联接名称?

标签 c# asp.net sql sql-server

我有一个具有SiteUserID,FirstName,LastName和SiteUserParentID的表SiteUsers。

每个SiteUser都分配有一个SiteUserParentID,该ID引用一个SiteUserID。

我想显示与SiteUser的全名以及分配给他们的人的全名的关系。

做这个的最好方式是什么?

    SiteUserID, FirstName, LastName ParentID
      1       , John     , Doe     , 1
      2       , Sallie   , Smith   , 1


我正在寻找的输出是:

ChildName   , ParentName
John Doe    , John Doe
Sallie Smith, John Doe


我当然想将其转储到asp.net中继器中,并使输出为:

John Doe is assigned to John Doe
Sallie Smith is assigned to John Doe


目前,我正在查看:

John Doe is assigned to 1
Sallie Smith is assigned to 1


使用以下内容:

    static public List<SiteUser> GetSiteUserListFullName()
{
    List<SiteUser> thelist = new List<SiteUser>();
    string sql = "select SiteUserID, SiteUserFirstName + ' ' + SiteUserLastName as SiteUserName, SiteUserParentID from SiteUsers where SiteUserActive = 1";
    SqlDataReader dr = DBUtil.FillDataReader(sql);

    while (dr.Read())
    {
        SiteUser obj = new SiteUser();

        obj.siteUserID = Convert.ToInt32(dr["siteUserID"].ToString());
        obj.siteUserFirstName = Convert.ToString(dr["siteUserName"].ToString());
        obj.siteUserParentID = Convert.ToInt32(dr["siteUserParentID"].ToString());
        thelist.Add(obj);
    }
    return thelist;
}


而这在我的代码后面:

    repeaterTeams.DataSource = SiteUser.GetSiteUserListFullName();
    repeaterTeams.DataBind();


而在前端:

<asp:Repeater ID="repeaterTeams" runat="server">
<HeaderTemplate>
    <table class="horTable">
    <tr class="tableHeader">
        <td class="first">Assignment</td>
        <td class="last">Edit</td>
    </tr>
</HeaderTemplate>
<ItemTemplate>
    <tr class="tableRow">
        <td><%#DataBinder.Eval(Container.DataItem, "SiteUserFirstName")%> is assigned to <%#DataBinder.Eval(Container.DataItem, "SiteUserParentID")%></td>
        <td class="last"><a href="selected-team.aspx?id=<%#DataBinder.Eval(Container.DataItem, "SiteUserID")%>">Select</a></td>
    </tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>




任何帮助表示赞赏。

谢谢!

最佳答案

您需要自己加入表格。

例:

select 
    child.SiteUserFirstName + ' ' + child.SiteUserLastName as ChildName,
    parent.SiteUserFirstName + ' ' + parent.SiteUserLastName as ParentName 
from 
    SiteUsers as child
inner join 
    SiteUsers as parent on child.SiteUserParentID = parent.SiteuserID
where 
    child.SiteUserActive = 1

关于c# - 如何在SQL中使用同一表联接名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7692403/

相关文章:

mysql - 每月分期付款发票的数据库设计

c# dapper error when parameter is list<int> 对象类型 <>f__AnonymousType20`1[[System.Int32[] 不存在映射

c# - 在 LINQ to SQL 中,如何将 LINQ 查询的一部分传递给函数

c# - 在 C# 中存储 SQL 结果

php - 我需要什么才能开始在 .NET 中进行开发

asp.net - 为什么 ServiceModel 有时在 Framework 文件夹的 Web.config 中声明,有时则不然?

sql - 在自定义聚合函数中查找 SUM 和 MAX

c# - MQRC_ 从 iSeries Websphere 消息队列获取消息时出错

c# - 获取数组子集,无需像 C 中的指针那样进行复制

jquery - 如何在 Repeater 中隐藏一个 div