如何从MySQL表中选择具有最大值的行

时间:2016-05-09 16:42:02

标签: php mysql

我有一个表,每个客户都有多行,还有一个visit_date。访问日期也可以为空。

我的表格如下:

客户:

id  |  name      | email 
1   |  John Doe1 | a.b@gmail.com 
2   |  John Doe2 | b.c@gmail.com
3   |  John Doe3 | x.y@gmail.com

store_customers

id |  customer_id  | store_id | email_optedin |  visit_date 
1  |     1         |   1      |   1         |   2015-11-30
2  |     1         |   2      |   1         |   2016-05-08
3  |     1         |   3      |   1         |    null
4  |     2         |   1      |   1         |   2015-04-30
5  |     2         |   2      |   1         |   2015-08-40
6  |     2         |   3      |   1         |   2015-12-12
7  |     3         |   1      |   1         |   null
8  |     3         |   2      |   1         |   null
9  |     3         |   3      |   1         |   null

我正在尝试检索那些未访问过三家商店中任何一家或自指定日期以来未访问过的客户(例如2016-04-15)。

我期待客户2和3但不是1。

我尝试了这个查询:

select distinct * from customers 
inner join store_customers on store_customers.customer_id = customers.id 
    where customers.email != '' and 
    store_customer.store_id in (1,2,3) and customers.emailStatus not in ('Unverified','Bounced','Spammed') 
    and 
    (
       store_customer.email_optedin = 1 
       and max(store_customers.visit_date) <= '2016-04-15'  
       or account_customer.visit_date is null
    );

这不起作用。我不知何故需要,对于商店ID的集合,我需要选择没有任何访问的客户(指定商店的访问日期的所有空值)或者如果一个或多个访问日期可用,则比较最大值日期到指定日期。

我发现了类似的问题,但没有一个答案对我有用,主要是因为需要选择那些没有访问的客户或者他们至少做过一个,然后比较一组商店的最新访问日期在联合表中。

我试图在一个查询中完成所有操作,但如果不可能,那么我也可以将其分解。我也不想更改连接的顺序,因为此查询中添加了许多其他内容,并且更改连接的顺序可能会成为问题。

我真的很感激可以提供任何帮助。

此致

瓦卡

1 个答案:

答案 0 :(得分:0)

尝试此查询

SELECT

        customers.id,
        customers.name,
        MAX(store_customers.visit_date)

    FROM

    customers LEFT JOIN store_customers on customers.id = store_customers.customer_id

    GROUP BY customers.id,customers.name

    HAVING MAX(store_customers.visit_date) < '2016-04-15' OR MAX(store_customers.visit_date) IS NULL