0

我正在尝试进行查询,If the customer has no invoice, but has an appointment in the last 6 months, please give me their clientId and name 显示以下结果返回和空集。

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_ADD 而不是 DATE_SUB 吗?

您可以使用连接:

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 回答