mirror of
https://github.com/dotnetcore/FreeSql.git
synced 2026-02-12 11:20:56 +08:00
Updated 多表查询 (markdown)
36
多表查询.md
36
多表查询.md
@@ -76,29 +76,27 @@ fsql.Select<Topic, Category, CategoryType>()
|
|||||||
|
|
||||||
> 经验:[一对多,分表只取最后一条记录](https://github.com/dotnetcore/FreeSql/issues/430)
|
> 经验:[一对多,分表只取最后一条记录](https://github.com/dotnetcore/FreeSql/issues/430)
|
||||||
|
|
||||||
## 3、WithSql
|
## 3、WithoutJoin
|
||||||
|
|
||||||
|
`WithoutJoin()` 方法提供了一种强大的机制,用于在 FreeSql 的多表查询(例如 `fsql.Select<T1, T2, T3>()`)中,**严格地控制哪些泛型类型对应的表最终会被 JOIN 到生成的 SQL 语句中**。这使得你可以在应用程序层面精确地动态构建查询,替代传统手动拼接 SQL 中对 JOIN 子句的条件控制。
|
||||||
|
|
||||||
```csharp
|
```csharp
|
||||||
fsql.Select<Topic, Category, CategoryType>()
|
fsql.Select<Order, Product, User>()
|
||||||
.WithSql(
|
.InnerJoin((o, p, u) => o.UserId == u.Id)
|
||||||
"select * from Topic where id=@id1",
|
.LeftJoin((o, p, u) => o.ProductId == p.Id)
|
||||||
"select * from Category where id=@id2",
|
.WithoutJoin(t2: !includeProductInfo)
|
||||||
null, //不设置 CategoryType 对应的 SQL
|
.ToList((o, p, u) => new OrderDetailDto
|
||||||
new { id1 = 10, id2 = 11, id3 = 13 }
|
{
|
||||||
)
|
OrderId = o.Id,
|
||||||
.LeftJoin((a,b,c) => a.CategoryId == b.Id)
|
OrderNo = o.OrderNo,
|
||||||
.LeftJoin((a,b,c) => b.ParentId == c.Id)
|
Username = u.Username, // User (T3) 始终 JOIN,可直接引用
|
||||||
.ToList();
|
ProductName = includeProductInfo ? p.Name : "N/A"
|
||||||
//SELECT ...
|
});
|
||||||
//FROM ( select * from Topic where id=@id1 ) a
|
|
||||||
//LEFT JOIN ( select * from Category where id=@id2 ) b ON a.`CategoryId` = b.`Id`
|
// includeProductInfo = true: SQL 将 JOIN Product
|
||||||
//LEFT JOIN `CategoryType` c ON b.`ParentId` = c.`Id`
|
// includeProductInfo = false: SQL 将不 JOIN Product,ProductName 会是 "N/A"
|
||||||
```
|
```
|
||||||
|
|
||||||
> 提示:ISelect.ToSql 可与 WithSql 配合使用
|
|
||||||
|
|
||||||
> v3.2.666 [WithTempQuery + FromQuery 嵌套查询](%e5%b5%8c%e5%a5%97%e6%9f%a5%e8%af%a2)
|
|
||||||
|
|
||||||
## 4、SQL联表
|
## 4、SQL联表
|
||||||
```csharp
|
```csharp
|
||||||
fsql.Select<Topic>()
|
fsql.Select<Topic>()
|
||||||
|
|||||||
Reference in New Issue
Block a user