mySQL SELECT介于日期和条件之间

时间:2016-04-28 14:01:33

标签: php mysql

我正在融化,我对SQL的体验在某种程度上是有限的,出于这些目的。假设我有以下两个表:

CUSTOMER_LIST:

id    |    email
-----------------------------------
1     |    mail1@mail.com
2     |    mail2@mail.com
3     |    mail3@mail.com

payment_log

customer_id    |    payment_date    |    payment_type_id
-------------------------------------------------------------
1              |    2016-01-01      |    3
1              |    2016-01-05      |    3
1              |    2016-01-02      |    2
1              |    2016-04-01      |    1
1              |    2016-04-12      |    2
2              |    2016-01-13      |    1
2              |    2016-01-19      |    1
2              |    2016-01-07      |    1
2              |    2016-01-04      |    1
3              |    2016-04-15      |    2

我希望选择的客户必须符合以下条件:

  • 必须在2016-03-22之前付款,任何付款方式,不包括payment_type_id = 3.

  • 必须在2016-03-22之后至少使用payment_type_id = 3进行一次付款。

作为查询结果我需要的客户是customer_id = 1.

4 个答案:

答案 0 :(得分:1)

我认为你应该在同一个表上使用内连接

SELECT distinct a.customer_id FROM payment_log  as a
INNER JOIN payment_log as b 
        on (a.customer_id = b.customer_id and a.payment_date = b.payment_date)
WHERE (a.payment_date < '2016-03-22' AND a.payment_type_id!=3)
AND  (b.payment_date>2016-03-22 AND b.payment_type_id=3)";

答案 1 :(得分:0)

试试这个。

SELECT customer_id 
FROM payment_log 
WHERE payment_date =< '2016-03-22' AND payment_type_id != '3');

答案 2 :(得分:0)

尝试类似:

SELECT 
  DISTINCT customer_id 
FROM 
  payment_log 
WHERE 
    (payment_date < '2016-03-22' AND payment_type_id != 3) 
  AND 
    customer_id IN (SELECT DISTINCT customer_id FROM payment_log WHERE payment_date > 2016-03-22 AND payment_type_id = 3);

您可能需要按一下sql语法,但它应该能满足您的需求。

答案 3 :(得分:0)

{{1}}