如何优化这个慢速MSSQL查询?

时间:2015-07-09 05:47:22

标签: sql-server

这是我的mssql查询:

    SELECT  ROW_NUMBER() OVER(ORDER BY ii.item_id ASC) AS Row,
        ii.item_id, 
        ii.item_description, 
        ii.item_function_id, 
        ib.brand_name, 
        if.name, 
        ipr.part_number, 
        ipr.default_part_number, 
        imn.model_name , 
        imn.is_default,
        img.model_group_name, 
        ims.model_series_name , 
        imf.model_family_name, 
        icg.name as cig_name, 
        ips.proxy_set_name, 
        icn.cartridge_name, 
        (SELECT SUM((quantity - quantity_on_hold - quantity_unposted) * uofm) FROM warehouse_inventory where  sage_item_id = ii.item_id) as qty, 
        ip.item_price FROM ii  

LEFT JOIN ib ON ib.brand_id = ii.brand_id
LEFT JOIN if ON if.id = ii.item_function_id
LEFT JOIN ipr ON ipr.item_id = ii.item_id

LEFT JOIN imn ON imn.model_id in 
    (SELECT  frv.child FROM frv WHERE frv.id = 4 AND frv.parent in 
        (SELECT  frv.parent FROM frv WHERE frv.id = 5 AND frv.child = ii.item_id ) )

LEFT JOIN img on img.model_group_id in 
        (SELECT  frv.parent FROM frv WHERE frv.id = 5 AND frv.child = ii.item_id ) 

LEFT JOIN imf on imf.model_family_id in 
    (SELECT  frv.child FROM frv WHERE frv.id = 15 AND frv.parent in
            (SELECT  frv.parent FROM frv WHERE frv.id = 5 AND frv.child = ii.item_id ) ) 

LEFT JOIN ims on ims.model_series_id in 
    (SELECT  frv.parent FROM frv WHERE frv.id = 9 AND frv.child in
        (SELECT  frv.child FROM frv WHERE frv.id = 4 AND frv.parent in 
            (SELECT  frv.parent FROM frv WHERE frv.id = 5 AND frv.child = ii.item_id ) ) )

LEFT JOIN icg ON icg.item_compatible_group_id in 
    (SELECT  frv.parent FROM frv WHERE frv.id = 25 AND frv.child = ii.item_id )

LEFT JOIN ips ON ips.proxy_set_id in 
    (SELECT  frv.parent FROM frv WHERE frv.id = 2 AND frv.child = ii.item_id )

LEFT JOIN icn ON icn.cartridge_id in 
    (SELECT  frv.child FROM frv WHERE frv.id = 13 AND frv.parent = ii.item_id )

LEFT JOIN ip ON ip.item_id = ii.item_id AND ip.sales_interface_id = 40

WHERE ii.is_deleted = 'false' 
ORDER BY ii.item_id  ASC
OFFSET 0 ROWS FETCH NEXT 100 ROWS ONLY

任务是从db前100个项目中获取并将它们放在表格中。问题是:列part_numbermodel_name具有相同item_id的多个值,因此在执行此查询时,如果项目具有100个不同的model_names,则会显示100次。因为这个“OFFSET 0 ROWS FETCH NEXT 100 ROWS ONLY”无效。有什么方法可以解决这个问题并优化查询吗?

我正在使用coldfusion并且有一种方法可以隐藏所有重复项(),但是当我尝试显示100个不同的项目时(获取503错误),查询无效。例如,当我设置“OFFSET 0 ROWS FETCH NEXT 5000 ROWS ONLY”时,我只能在表格中显示39个不同的行。

1 个答案:

答案 0 :(得分:0)

你应该加入一个在加入之前已经过的表格。

您可以使用CTE或OUTER APPLY (SELECT DISTINCT... FROM item_model_name )

不知道你的数据,但是" TOP 1"也可以帮忙。