我很难弄清楚如何对代码中没有相互引用的 2 个表执行查询,例如,我有
Customer -> Product* where customer and product have reference to each other
和库存 -> 产品*,其中产品没有参考库存
我想找到所有没有库存的客户。
到目前为止我已经这样做了
var subQueryInv= DetachedCriteria.For<Inventory>();
subQueryInv
.Add(Restrictions.IsNotNull("Product.Id"))
.SetProjection(Projections.Property<Inventory>(inv=> inv.Product.Id));
var subQueryProd = DetachedCriteria.For<Product>();
subQueryTire
.Add(Subqueries.PropertyNotIn("Id", subQueryInv))
.SetProjection(Projections.Property<Tire>(prod=> prod.Customer.Id));
var subQueryCust= DetachedCriteria.For<Customer>();
subQueryCust
.Add(Subqueries.PropertyIn("Id", subQueryProd))
.SetProjection(Projections.Property<TireSet>(cust => cust.Id));
那行得通,bt查询效率很低,它为库存部分生成这样的SQL ...WHERE Product.Id NOT IN (SELECT Inventory.ProductId FROM Inventory WHERE Inventory.ProductId IS NOT NULL)
因此,对于每条产品记录,它都在查询整个 Inventory 表。如何让子查询具有对父 ID 的引用,如下所示:
...WHERE Product.Id NOT IN (SELECT Inventory.ProductId FROM Inventory WHERE Inventory.ProductId IS NOT NULL AND Inventory.ProductId = Product.Id)
?