我正在尝试创建一个查询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)
答案 0 :(得分: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)
答案 1 :(得分: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