Dataset Datatable 关联查询

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {

            // construct table 't1'
            DataTable t1 = new DataTable("t1");
            t1.Columns.Add("a", typeof(string));
            t1.Columns.Add("b", typeof(string));
            t1.Columns.Add("c", typeof(string));
            t1.Constraints.Add("pk_t1_a", t1.Columns["a"], true);
            t1.Rows.Add("a1", "b1", "c1");
            t1.Rows.Add("a2", "b2", "c2");
            t1.Rows.Add("a3", "b3", "c3");
            t1.Rows.Add("a4", "b4", "c4");

            // construct table 't2'
            DataTable t2 = new DataTable("t2");
            t2.Columns.Add("h", typeof(string));
            t2.Columns.Add("i", typeof(string));
            t2.Constraints.Add("pk_t2_h", t2.Columns["h"], true);

            t2.Rows.Add("a1", "h1");
            t2.Rows.Add("a2", "h2");
            t2.Rows.Add("ax", "hx");

            // construct a dataset
            DataSet ds = new DataSet("select demo");
            ds.Tables.AddRange(new DataTable[] { t1, t2 });

            // perform. query
            ds.Relations.Add(new DataRelation("pk_t1_t2_a1_h1", t1.Columns["a"], t2.Columns["h"], false));
            DataRow[] parentRows = ds.Tables["t1"].Select("a='a1'");
            // parse result
            foreach (DataRow parentRow in parentRows)
            {
                // use GetChildRows to get the extra data
                DataRow[] childRows = parentRow.GetChildRows("pk_t1_t2_a1_h1");
                // to be contined...
            }
        }
    }
}


------------------------------------------------------

问题:

datatable t1 有a,b,c,d,e   五列
datatable t2 有h,i,j,k     四列

关联条件:

t1.a = t2.h
t1.b = t2.i
t1.c = t2.j

求结果:
t1的全部和t2.k

结果table t3:
(共六列)

a   b   c   d   e   k


-----------------------------------------------------

select t1.*, t2.k from t1,t2 where t1.a = t2.h and t1.b = t2.i and t1.c = t2.j

 

 

 

 

 

 

请使用浏览器的分享功能分享到微信等