負載參考負載1查詢加載主表和1查詢到不論加載的子引用多少行有孩子的引用。
你可以看到通過查看當你使用一個ConsoleLogFactory
產生的真實被記錄到控制檯輸出SQL生成的SQL。比如這裏有一個LoadSelect
example you can run on Gistlyn其控制檯輸出:
public class Artist
{
public int Id { get; set; }
public string Name { get; set; }
[Reference]
public List<Track> Tracks { get; set; }
public override string ToString() => Name;
}
public class Track
{
[AutoIncrement]
public int Id { get; set; }
public string Name { get; set; }
public int ArtistId { get; set; }
public string Album { get; set; }
public int Year { get; set; }
public override string ToString() => Name;
}
var oldestTracks = db.Select(db.From<Track>()
.Where(x => Sql.In(x.Year, db.From<Track>().Select(y => Sql.Min(y.Year)))));
"Oldest Tracks: {0}".Print(oldestTracks.Dump());
var oldestTrackIds = oldestTracks.Map(x => x.Id);
var earliestArtistsWithRefs = db.LoadSelect(db.From<Artist>()
.Where(a => oldestTracks.Map(t => t.ArtistId).Contains(a.Id)));
"Earliest Artists: {0}".Print(earliestArtistsWithRefs.Dump());
控制檯輸出:
DEBUG: SQL: SELECT "Id", "Name"
FROM "Artist"
WHERE "Id" In (@0,@1)
PARAMS: @0=3, @1=4
DEBUG: SQL: SELECT "Id", "Name", "ArtistId", "Album", "Year" FROM "Track" WHERE "ArtistId" IN (SELECT "Artist"."Id"
FROM "Artist"
WHERE "Id" In (@0,@1))
PARAMS: @0=3, @1=4
Earliest Artists: [
{
Id: 3,
Name: Nirvana,
Tracks:
[
{
Id: 5,
Name: Smells Like Teen Spirit,
ArtistId: 3,
Album: Nevermind,
Year: 1991
},
{
Id: 6,
Name: Heart-Shaped Box,
ArtistId: 3,
Album: In Utero,
Year: 1993
}
]
},
{
Id: 4,
Name: Pearl Jam,
Tracks:
[
{
Id: 7,
Name: Alive,
ArtistId: 4,
Album: Ten,
Year: 1991
},
{
Id: 8,
Name: Daughter,
ArtistId: 4,
Album: Vs,
Year: 1993
}
]
}
]
在那裏你可以看到2個查詢,1個查詢加載主表和1個查詢加載曲目孩子引用。
謝謝@mythz。主表查詢是複雜的和資源密集型的,所以我最終通過'Select' API執行它,然後在參考表上對主查詢中的唯一ID執行單獨的查詢,最後合併兩個結果集。在我的情況下,它比'LoadSelect'更快,更優化,它將主查詢重新作爲參考查詢運行。我想這種方法的一個警告是,主查詢中唯一Id的數量必須合理,以避免超過IN條款的參數限制。 – Nick