FreeSql (十九)多表查询

多表查询,常用的有联表 LeftJoin/InnerJoin/RightJoin ,这三个方法在上篇文章已经介绍过。

除了联表,还有子查询 Where Exists,和 Select 子表:

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; }
}

子表 Exists

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))

子表 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)
});

系列文章导航

转载于:https://www.cnblogs.com/FreeSql/p/11531362.html

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值