SQL LEFT JOIN TABLE导致一些错误

时间:2016-08-03 07:44:20

标签: sql

SELECT COUNT(ORVM.APPID) AS 'Number of VMs', ORAP.ORDERID
    FROM    Order.[VirtualMachine] ORVM,
        Order.[Application] ORAP,
        Order.[ServiceOrder] SO
    WHERE   SO.ORDERID=ORAP.ORDERID AND
        ORAP.APPID=ORVM.APPID
    GROUP BY ORAP.ORDERID
SELECT COUNT(ORVM.APPID) AS 'Number of VMs', ORAP.ORDERID
  FROM  Order.[ServiceOrder] SO,
    Order.[Application] ORAP
  LEFT JOIN Order.[VirtualMachine] ORVM
  ON ORAP.APPID=ORVM.APPID
  WHERE SO.ORDERID=ORAP.ORDERID
  GROUP BY ORAP.ORDERID

表名:ORAP

APPID   ORDERID APPNAME
2   6   A
3   7   B
4   8   C
5   9   D
6   10  E
9   11  F

表名:ORVM

VMID    APPID   VMNAME
4   2   AA-1
5   2   AA-2
6   2   AA-3
33  5   BB-1
34  6   CC-1
35  6   CC-2
36  6   CC-3
37  6   CC-4
38  10  DD-1
39  10  DD-2
40  10  DD-3
41  9   EE-1

表名:SO

ORDERID ORDERNUM    STATUS
6   OR000001    NORMAL
7   OR000002    NORMAL
8   OR000003    NORMAL
9   OR000004    NORMAL
10  OR000005    NORMAL
11  OR000006    NORMAL

我想搜索每个APP有多少个虚拟机,SQL 1输出正确,SQL 2输出错误。我想找出原因并使SQL 2正确。

1 个答案:

答案 0 :(得分:1)

如果使用join,则必须始终执行:不要使用where和join语法混合隐式连接

SELECT 
    COUNT(ORVM.APPID) AS 'Number of VMs', ORAP.ORDERID
FROM  
    Order.[ServiceOrder] SO 
JOIN
    Order.[Application] ORAP ON SO.ORDERID = ORAP.ORDERID
LEFT JOIN 
    Order.[VirtualMachine] ORVM ON ORAP.APPID = ORVM.APPID
GROUP BY 
    ORAP.ORDERID

我不确定这会解决您的错误,因为您没有添加错误消息。