1

正如标题所说,我正在尝试查找已下订单但尚未付款的客户。

我有三张桌子;

Customers, Payments, Orders

到目前为止,我的 sql 给了我(嵌套查询)所有没有付款的客户,然后外部查询尝试将所有客户与订单连接起来,并检查这些客户是否不在我的内部表中?

SELECT customerWOpayments.customerNumber FROM 
ClassicModels.Customers c
INNER JOIN ClassicModels.Orders o ON c.customerName = o.customerNumber
NOT IN 
(SELECT  distinct c.customerNumber
FROM ClassicModels.Customers c
LEFT OUTER JOIN ClassicModels.Payments p ON c.customerNumber = p.customerNumber
WHERE p.customerNumber IS NULL) customerWOpayments;

我在第 8 行收到一个 mysql 语法错误,但不知道为什么?

4

3 回答 3

2

假设您在原始示例中加入的所有键都是正确的(例如 c.customerName = o.customerNumber 似乎可疑),这应该返回有订单但没有匹配付款的客户。

SELECT c.customerNumber
FROM ClassicModels.Customers c
  INNER JOIN ClassicModels.Orders o
    ON c.customerNumber = o.customerNumber
  LEFT OUTER JOIN ClassicModels.Payments p
    ON c.customerNumber = p.customerNumber
WHERE p.customerNumber IS NULL;
于 2012-02-12T04:26:13.343 回答
1

基本上你错过了这个WHERE条款。你的问题缺乏信息。请提供Schema您的桌子。谢谢!

试试这个:

你确定有这个条件ON c.customerName = o.customerNumber吗?

SELECT customerWOpayments.customerNumber 
FROM  ClassicModels.Customers c INNER JOIN ClassicModels.Orders o 
         ON c.customerName = o.customerNumber -- Please check this out
WHERE o.customerNumber NOT IN 
    (SELECT  distinct c.customerNumber
    FROM ClassicModels.Customers c LEFT JOIN ClassicModels.Payments p 
             ON c.customerNumber = p.customerNumber
    WHERE p.customerNumber IS NULL);

或没有子查询

SELECT a.*
FROM Customers a INNER JOIN Orders b ON
        a.CustomerName = b.CustomerNumber -- Please check this line
     LEFT JOIN Payments c ON
        b.CustomerNumber = c.CustomerNumber
WHERE c.CustomerNumber IS NULL

我相信这是一个错字错误a.CustomerName = b.CustomerNumber,而不是a.CustomerNumber = b.CustomerNumber

我无法准确判断是不是因为您没有为schema您的桌子提供一些dummy records.

希望这可以帮助。

于 2012-02-12T04:23:37.660 回答
0

与其他解决方案不同,当客户有多个订单时,此解决方案不会产生重复的客户编号。

SELECT C.customerNumber 
FROM ClassicModels.Customers C 
WHERE 
EXISTS(
    -- customer has orders
    SELECT * 
    FROM ClassicModels.Orders AS O
    WHERE O.customerNumber = C.customerNumber 
)
AND NOT EXISTS(
    -- customer does not have payments
    SELECT *
    FROM ClassicModels.Payments P
    WHERE P.customerNumber = C.customerNumber
)
于 2012-02-12T05:09:48.657 回答