MySQL:联接表中的最大日期小于

时间:2018-11-27 06:48:14

标签: mysql sql

我有3个表-clientinvoiceinvoice_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 个答案:

答案 0 :(得分:3)

您可以在子查询中按发票的标识符对数据进行分组,但是应该在子查询中按client_id对数据进行分组。

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.client_id
            ) joined
ON joined.clid = c.id
WHERE joined.mdt  < date('2017-01-01')