簡體   English   中英

復雜的SQL子查詢到LINQ

[英]Complex SQL Subquery to LINQ

我有這個SQL查詢,這在LINQ中是不可能的。

select * from attribute_value t0
where t0.attribute_value_id in
(
    select t1.attribute_value_id from product_attribute_value t1
    where t1.product_attribute_id in
    (
        select t2.product_attribute_id from product_attribute t2
        where t2.product_id in
        (
            select product_id from product p, manufacturer m
            where p.manufacturer_id = m.manufacturer_id
            and m.name = 'manufacturer name'
        )
        and pa.attribute_id = 1207
    )
)

where子句也必須稍后在代碼中動態完成。

嘗試使用Linqer 我記得用它寫了一些非常復雜的東西。

另外,您的查詢並不是那么復雜,您只是從產品到其屬性值。 只需在鍵上做很多連接就可以了。

我喜歡通過將查詢的離散組件編寫為單獨的語句來編寫Linq查詢。 因為每個語句都是查詢而不是結果,所以Linq會在運行時將這些全部組合成一個SQL查詢。

對我來說,以這種方式編寫查詢使得它非常容易閱讀,而不會犧牲運行時數據庫的性能,因為Linq無論如何都會在運行時將它變成一個大的查詢。 它會將以下查詢中的Contains轉換為子選擇。

使用LinqPad查看生成的SQL - 查看SQL Linq創建的內容非常有趣。

注意結果本身就是一個查詢。 要實現它,請執行result.ToList();

var productIds = from p in product
                 join m in manufacturer on p.manufacturer_id equals m.manufacturer_id
                 where m.name == 'manufacturer name'
                 select p.product_id;

var productAttributeIds =  from pa in product_attribute
                           where productIds.Contains(pa.product_id)
                           select pa.product_attribute_id;

var attributeValueIds = from pav in product_attribute_value
                        where productAttributeIds.Contains(pav.product_attribute_id)
                        select pav.attribute_value_id;

result = from av in attribute_value
         where attributeValueIds.Contains(av.atttriute_value_id)
         select av;

我已經使用Contains()方法成功實現了'in'查詢。 例如:

int[] ids = new int[] { 1, 4 };

databasecontext.SomeTable.Where(s => ids.Contains(s.id));

以上將返回SomeTable的所有記錄,其中id為1或4。

我相信你可以將Contains()方法鏈接在一起。 我知道它似乎倒退了,但從最里面的subselect開始,然后從那里開始。

取決於模型,但您應該能夠這樣做:

var attributes =
    from t0 in db.AttributeValues
    where t0.ProductAttributeValues.Any( t1=> 
        t1.ProductAttribute.AttributeId == 1207 &&
        t1.ProductAttribute.Product.Manufacturers
             .Any(m=> m.name == "manufacturer name")
    )
    select t0;

另一種方法,與查詢/只是翻譯方法相似:

var attributes =
    from t0 in db.AttributeValues
    where db.Product_Attribute_Values.Any(t1 => 
        db.Product_Attributes.Any(t2 =>
            t2.product_attribute_id == t1.product_attribute_id &&
            db.Products.Any(p=> 
                 p.product_id == t2.product_id &&
                 db.Manufacturers.Any(m=> 
                      m.manufacturer_id == p.manufacturer_id && 
                      m.name == "manufacturer name"
                 )
            ) &&
            t2.attribute_id = 1207
        ) &&
        t0.attribute_value_id == t1.attribute_value_id
     )
     select t0;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM