使用其他表中的值访问c#中表的值

时间:2014-05-12 04:39:51

标签: c# sql

我有两张名为myfriends和imageslikes的表。在我的代码中,我试图访问表myfriends的列id2,并基于该列中的每个值,我想访问imageslikes表的记录。但是对于我的代码,我只获得了值,因为转发器的输出可能因为它被覆盖了。

访问我想要的所有记录的可能解决方案是什么?有人可以帮忙吗?

        Query = "select id2 from myfriends where id1 = '" + Session["id"] + "'";
        adap = new SqlDataAdapter(Query, con);
        ds = new DataSet();
        adap.Fill(ds);
        dt = ds.Tables[0];
        dr = dt.Rows[0];
        foreach (DataRow row in dt.Rows)
        {
            string id2 = row["id2"].ToString();
            Query = "select * from imageslikes where likedby = '" + id2 + "'";
            adap = new SqlDataAdapter(Query, con);
            ds = new DataSet();
            adap.Fill(ds);
            DataList4.DataSource = ds;
            DataList4.DataBind();



        }

2 个答案:

答案 0 :(得分:1)

        Query = "select * from imageslikes where likedby=(select id2 from myfriends where id1 = '" + Session["id"] + "') ";

答案 1 :(得分:0)

    Query = "select id2 from myfriends where id1 = '" + Session["id"] + "'";
adap = new SqlDataAdapter(Query, con);
ds = new DataSet();
adap.Fill(ds);
dt = ds.Tables[0];
dr = dt.Rows[0];
foreach (DataRow row in dt.Rows)
{
    string id2 = row["id2"].ToString();
    Query = "select * from imageslikes where likedby = '" + id2 + "'";
    adap = new SqlDataAdapter(Query, con);
    ds = new DataSet();
    adap.Fill(ds);
    DataList4.DataSource = ds;
    DataList4.DataBind();

    //Added this line
    ds = new DataSet();
    //if you need both records related to id1 and id2 then use
    Query = "select * from imageslikes where likedby in ('" + id2 + "', '" + id1 + "')";

    //Query = "select * from imageslikes where likedby = '" + id2 + "'";
    adap = new SqlDataAdapter(Query, con);
    ds = new DataSet();
    adap.Fill(ds);
    Repeater3.DataSource = ds;
    Repeater3.DataBind(); 


}