0

If the customer has no invoice, but has an appointment in the last 6 months, please give me their clientId and name The following result returns and empty set.というクエリを作成しようとしています。

SELECT clients.clientId, clients.studentFirstName, clients.studentLastName 
FROM  clients, invoices, appointments 
WHERE (NOT EXISTS 
          (SELECT * 
           FROM invoices, clients 
           WHERE invoices.clientId = clients.clientId)) 
AND (EXISTS 
         (SELECT * FROM appointments, clients 
         WHERE appointments.clientId = invoices.clientId 
         AND appointments.date >= DATE_ADD(curdate(), INTERVAL 6 MONTH)));

編集:最終的に機能するクエリは、ジョンの回答を少し調整した後に作成されました:

 SELECT  a.clientID,
    a.studentFirstName,
    a.studentLastName
FROM    clients a 
        LEFT JOIN invoices b
            on a.clientID = b.clientID
        LEFT JOIN appointments c
            on a.clientID = c.clientID
WHERE   b.clientId IS NULL AND
    c.`date` >= DATE_SUB(curdate(), INTERVAL 6 MONTH)
4

2 に答える 2

3

LEFT JOIN代わりに使用してください。

SELECT  a.ClientID,
        a.studentFirstName,
        a.clients.studentLastName
FROM    clients a 
            LEFT JOIN invoices b
                on a.ClientID = b.ClientID
            LEFT JOIN appointments c
                on a.ClientID = c.ClientID
WHERE   b.Client IS NULL AND
        c.`Date` >= DATE_SUB(curdate(), INTERVAL 6 MONTH)
于 2012-07-15T02:38:23.957 に答える
0

DATE_SUB ではなく DATE_ADD であるはずですか?

結合を使用できます:

SELECT    a.clientId,
          a.studentFirstName,
          a.studentLastName
FROM      clients a
JOIN      appointments b ON a.clientId = b.clientId 
          AND b.date >= CURDATE() - INTERVAL 6 MONTH
LEFT JOIN invoices c ON a.clientId = c.clientId
WHERE     c.clientId IS NULL
于 2012-07-15T02:35:51.597 に答える