Multi-table queries, commonly used contingency table LeftJoin / InnerJoin / RightJoin, these three methods in the article has been introduced.
In addition to linking table, and subquery Where Exists, and Select the child table:
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; }
}
Child table 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)
});