1

As the title says, i am trying to find the customer's who have made orders but have not made payments yet.

I have Three tables;

Customers, Payments, Orders

The sql i have so far gives me (nested query) all the customers without payments, the outer query then tries to join all the customers with orders and checks if those customers are not in my inner table?

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;

I am getting a mysql syntax error at line 8 but cannot figure out why?

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);

OR サブクエリなし

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 に答える