ITPub博客

首页 > Linux操作系统 > Linux操作系统 > Dataset Datatable 关联查询

Dataset Datatable 关联查询

原创 Linux操作系统 作者:kirinri 时间:2009-06-07 22:19:00 0 删除 编辑

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

 

 

 

 

 

 

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/12476590/viewspace-605400/,如需转载,请注明出处,否则将追究法律责任。

下一篇: 陌生的短信
请登录后发表评论 登录
全部评论

注册时间:2007-12-21

  • 博文量
    257
  • 访问量
    497801