SQL Server产品价格并列

时间:2013-06-07 12:14:04

标签: sql-server sql-server-2008 tsql

SELECT     
    tbStok.sModel AS Kod, tbStok.sAciklama AS Adı, 
    SF.lFiyat AS SF, PSF.lFiyat AS PSF, 
    TL.lFiyat AS TL , USD.lFiyat AS USD
FROM         
    tbStok 
LEFT JOIN 
    tbStokFiyati AS TL ON tbStok.nStokID =  TL.nStokID 
LEFT JOIN 
    tbStokFiyati AS SF ON tbStok.nStokID =  SF.nStokID
LEFT JOIN 
    tbStokFiyati AS PSF ON tbStok.nStokID = PSF.nStokID 
LEFT JOIN 
    tbStokFiyati AS USD ON tbStok.nStokID = USD.nStokID
GROUP BY 
    tbStok.sModel, tbStok.sAciklama, SF.lFiyat, PSF.lFiyat, TL.lFiyat,USD.lFiyat

上面是我正在使用的SQL语句。

当查询开始时,结果是7255470行,但我在tBstok表中有18867行。

我们在tbStok表中包含产品信息,其中包含2个不同的列,例如产品代码和产品名称。在另一个名为tbStokFiyati的表中,我需要有4个不同的列。

结果很慢!

2 个答案:

答案 0 :(得分:0)

表格需要与tbStokFiyati分开。


SELECT     
    tbStok.sModel AS Kod, tbStok.sAciklama AS Adı, 
    SF.lFiyat AS SF, PSF.lFiyat AS PSF, 
    TL.lFiyat AS TL , USD.lFiyat AS USD  
FROM   tbStok 

LEFT JOIN 
    tbStokFiyati AS TL ON tbStok.nStokID =  TL.nStokID 
                      and TL.sFiyatTipi='TL'

LEFT JOIN tbStokFiyati AS SF ON tbStok.nStokID =  SF.nStokID
                      and SF.sFiyatTipi='SF'

LEFT JOIN tbStokFiyati AS PSF ON tbStok.nStokID = PSF.nStokID 
                      and PSF.sFiyatTipi='PSF'

LEFT JOIN tbStokFiyati AS USD ON tbStok.nStokID = USD.nStokID
                      and USD.sFiyatTipi='USD'

GROUP BY 
    tbStok.sModel, tbStok.sAciklama, SF.lFiyat, PSF.lFiyat, TL.lFiyat,USD.lFiyat

答案 1 :(得分:-1)

在运行此类性能问题时,您应该重新审视的第一件事是数据库设计。是否已相应定义PK?您是否在每个FK上创建了非聚集索引来查看联接?您是否在查询中使用的有趣列上创建了索引?您可以在SQL Server Management Studio上使用一项名为 实际执行计划 的功能来检查查询性能出了什么问题。

请查看SQL Server Index Basics以获取进一步的参考 还有一些用于基本和高级执行计划理解的实用链接:
* http://www.simple-talk.com/sql/performance/execution-plan-basics/
* http://www.mssqltips.com/sqlservertip/1856/sql-server-query-execution-plans-in-sql-server-management-studio/

Actual和Esitmated执行计划之间的区别:
* http://blog.sqlauthority.com/2007/08/28/sql-server-actual-execution-plan-vs-estimated-execution-plan/