SQL为什么这个连接不起作用?

时间:2012-05-28 15:42:18

标签: sql sql-server

我有以下SQL:

SELECT tab4.IRSpot as IRSpot, tab4.IRVol AS MaxPlauShift, tab4.VegElement AS MaxPlauLoss FROM
    (SELECT tab1.IRSpot, MIN(tab1.VegaElement*Probability) AS PlausibleLoss FROM
        (SELECT IRSpot, IRVol, VegaElement 
        FROM SEL_VegaElementMatrix()) tab1
    JOIN
        (SELECT IRSpot, IRVol, Probability 
        FROM Table_Name_2) tab2
    ON tab1.IRSpot = tab2.IRSpot AND tab1.IRVol = tab2.IRVol
    GROUP BY tab1.IRSpot) tab3
JOIN
    (SELECT IRSpot, IRVol, VegaElement 
    FROM SEL_VegaElementMatrix()) tab4
ON tab3.PlausibleLoss = tab4.VegaElement AND tab3.IRSpot = tab4.IRSpot

tab3返回一行{2,0},tab4返回许多行,其中八行包含相同的值{2,0}。

我期待我的联接返回八行结果,因为我正在执行JOIN但我只返回一个结果行?

1 个答案:

答案 0 :(得分:2)

将其更改为RIGHT JOIN以找出不匹配的内容。 INNER JOIN仅显示在两个表中找到匹配的行。我怀疑它是最终where / on子句中的东西,但是没有看到表结构和数据,很难说。

SELECT tab4.IRSpot as IRSpot, tab4.IRVol AS MaxPlauShift, tab4.VegElement AS MaxPlauLoss FROM 
    (SELECT tab1.IRSpot, MIN(tab1.VegaElement*Probability) AS PlausibleLoss FROM 
        (SELECT IRSpot, IRVol, VegaElement  
        FROM SEL_VegaElementMatrix()) tab1 
    JOIN 
        (SELECT IRSpot, IRVol, Probability  
        FROM Table_Name_2) tab2 
    ON tab1.IRSpot = tab2.IRSpot AND tab1.IRVol = tab2.IRVol 
    GROUP BY tab1.IRSpot) tab3 
RIGHT JOIN 
    (SELECT IRSpot, IRVol, VegaElement  
    FROM SEL_VegaElementMatrix()) tab4 
ON tab3.PlausibleLoss = tab4.VegaElement AND tab3.IRSpot = tab4.IRSpot