FreeSql 教程 (十九)多表查询
2020-03-14 本文已影响0人
叶先生_34e6
FreeSql 以 MIT 开源协议托管于 github:https://github.com/2881099/FreeSql
多表查询,常用的有联表 LeftJoin/InnerJoin/RightJoin ,这三个方法在上篇文章已经介绍过。
除了联表,还有子查询 Where Exists,和 Select 子表:
static 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(); //请务必定义成 Singleton 单例模式
[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; }
}
1、子表Exists
var list2 = fsql.Select<Topic>()
.Where(a => fsql.Select<Topic>().As("b").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`)))
提示:由于子查询的实体类与上层相同,使用 As("b") 指明别名,以便区分
2、子表In
var list2 = fsql.Select<Topic>()
.Where(a => fsql.Select<Topic>().As("b").ToList(b => b.Id).Contains(a.Id))
.ToList();
// SELECT a.`Id`, a.`Clicks`, a.`TypeGuid`, a.`Title`, a.`CreateTime`
// FROM `tb_topic` a
// WHERE (((cast(a.`Id` as char)) in (SELECT b.`Title`
// FROM `tb_topic` b)))
3、子表First/Count/Sum/Max/Min/Avg
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)
});
4、AsSelect
fsql.Select<TestTypeInfo>()
.Where(a => a.Topics.AsSelect().Any(b => b.Title.Contains("xx")))
.ToSql();
效果等同于:
fsql.Select<TestTypeInfo>()
.Where(a => fsql.Select<Topic>().Any(b => b.Title.Contains("xx")))
.ToSql();
将集合属性快速转换为 ISelect 进行子查询操作。
系列文章导航
-
(十九)多表查询