多表查詢,經常使用的有聯表 LeftJoin/InnerJoin/RightJoin ,這三個方法在上篇文章已經介紹過。html
除了聯表,還有子查詢 Where Exists,和 Select 子表:sql
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) });