FreeSql(XIX)マルチテーブルクエリ

マルチテーブルのクエリは、一般的に使用される分割表LeftJoin / InnerJoin / RightJoinは、これらの三つの方法の記事が紹介されました。

テーブルをリンクすることに加えて、サブクエリがどこに存在し、子テーブルを選択します。

IFreeSql fsql = new FreeSql.FreeSqlBuilder()
    .UseConnectionString(FreeSql.DataType.MySql, "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=10")
    .Build();

[Table(Name = "tb_topic")]
class Topic {
    [Column(IsIdentity = true, IsPrimary = true)]
    public int Id { get; set; }
    public int Clicks { get; set; }
    public int TestTypeInfoGuid { get; set; }
    public string Title { get; set; }
    public DateTime CreateTime { get; set; }
}

子テーブルが存在します

var sql2222 = fsql.Select<Topic>().Where(a => fsql.Select<Topic>().Where(b => b.Id == a.Id).Any()).ToList();
// SELECT a.`Id`, a.`TypeGuid`, a.`Title`, a.`CreateTime` 
// FROM `xxx` a 
// WHERE (exists(SELECT 1 
// FROM `xxx` b 
// WHERE (b.`Id` = a.`Id`)))

//两级相同的子表查询
sql2222 = fsql.Select<Topic>().Where(a =>
    fsql.Select<Topic>().Where(b => b.Id == a.Id && fsql.Select<Topic>().Where(c => c.Id == b.Id).Where(d => d.Id == a.Id).Where(e => e.Id == b.Id)
    .Offset(a.Id)
    .Any()
    ).Any()
).ToList();
// SELECT a.`Id`, a.`TypeGuid`, a.`Title`, a.`CreateTime` 
// FROM `xxx` a 
// WHERE (exists(SELECT 1 
// FROM `xxx` b 
// WHERE (b.`Id` = a.`Id` AND exists(SELECT 1 
// FROM `xxx` c 
// WHERE (c.`Id` = b.`Id`) AND (c.`Id` = a.`Id`) AND (c.`Id` = b.`Id`)
// limit 0,1))
// limit 0,1))

子表まず/カウント/和/最大/最小/平均

var subquery = fsql.Select<Topic>().ToSql(a => new {
    all = a,
    first = fsql.Select<Child>().Where(b => b.ParentId == a.Id).First(b => b.Id),
    count = fsql.Select<Child>().Where(b => b.ParentId == a.Id).Count(),
    sum = fsql.Select<Child>().Where(b => b.ParentId == a.Id).Sum(b => b.Score),
    max = fsql.Select<Child>().Where(b => b.ParentId == a.Id).Max(b => b.Score),
    min = fsql.Select<Child>().Where(b => b.ParentId == a.Id).Min(b => b.Score),
    avg = fsql.Select<Child>().Where(b => b.ParentId == a.Id).Avg(b => b.Score)
});

おすすめ

転載: www.cnblogs.com/FreeSql/p/11531362.html