我有三张table- client
, invoice
以及 invoice_item
. 我需要选择所有客户,最后购买日期小于特定日期。采购入库日期 invoice_item
表、分配给发票的项目和分配给客户的发票。这是我试过的
SELECT c.* FROM client c
INNER JOIN (
SELECT i.client_id as clid, MAX(item.date_created) as mdt
FROM invoice i
INNER JOIN invoice_item item on i.id = item.invoice_id
GROUP BY i.id
) joined
ON joined.clid = c.id
WHERE joined.mdt < date('2017-01-01')
还有
SELECT c.* FROM client c
WHERE c.id IN (
SELECT DISTINCT i.client_id FROM invoice i
INNER JOIN invoice_item item on i.id = item.invoice_id
GROUP BY i.id
HAVING MAX(item.date_created) < date('2017-01-01')
)
两个查询都返回错误的结果,下面是我用来检查正确性的查询:
SELECT MAX(invoice_item.date_created) FROM invoice_item
INNER JOIN invoice i on invoice_item.invoice_id = i.id
WHERE client_id = {some id from the previous query};
上面的查询返回日期,大于 2017-01-01
对一些客户来说。
我做错了什么?谢谢。
1条答案
按热度按时间1wnzp6jl1#
在子查询中按发票的标识符对数据进行分组,但在子查询中应按客户机id对数据进行分组。