使用 ServiceStack OrmLite 进行复杂的 JOIN

Complex JOIN with ServiceStack OrmLite

如何表达下面的查询(来自this question):

SELECT c.*, p1.*
FROM customer c
JOIN purchase p1 ON (c.id = p1.customer_id)
LEFT OUTER JOIN purchase p2 ON (c.id = p2.customer_id AND 
    (p1.date < p2.date OR p1.date = p2.date AND p1.id < p2.id))
WHERE p2.id IS NULL;

使用 OrmLite SelectJoin API?

不幸的是,你的 mutli tables self table join 太复杂了,无法在 OrmLite 的 Typed API 中表达,所以你需要下拉到 Custom SQL , 例如:

var results = db.Select<Tuple<Customer,Purchase>>(@"SELECT c.*, 0 EOT, p1.*
    FROM customer c
    JOIN purchase p1 ON (c.id = p1.customer_id)
    LEFT OUTER JOIN purchase p2 ON (c.id = p2.customer_id AND 
        (p1.date < p2.date OR p1.date = p2.date AND p1.id < p2.id))
    WHERE p2.id IS NULL;");

results.PrintDump();

我创建了一个 Live Example of this you can play with on Gistlyn