MYSQL从联接表中选择最大日期

时间:2018-07-17 13:19:11

标签: mysql sql database select max

我有2个表,我想加入它们并检索一些特定的数据。这些是我的桌子。

tbl_user (reg_id, l_name, f_name, status)

tbl_payments (pay_id, reg_id, mem_plan, from_date, to_date, bill_no, payed_date)

我需要做的是选择并查看应付款的用户。为此,我想从"status=0"中获取tbl_user的用户详细信息,并将2个表连接在一起,条件为to_date< current date[current date and the to_date] < 31之间的差异,并按最大值进行过滤值to_date

到目前为止,我所做的事情根据上述条件给出了结果,只是它没有被MAX(to_date)过滤。这是我的查询。

SELECT
       A.reg_id, 
       A.f_name, 
       A.l_name, 
       B.mem_plan, 
       B.from_date, 
       Max(B.to_date) AS to_date, 
       B.bill_no, 
       B.payed_date 
FROM
       tbl_user A, 
       tbl_payments B 
WHERE
       A.status = 0 
       AND A.reg_id = B.reg_id 
       AND Date(Now()) >= Date(B.to_date) 
       AND Datediff(Date(Now()), Date(b.to_date)) < 31
GROUP BY
       a.reg_id, b.mem_plan, b.from_date, b.bill_no, b.payed_date; 

我对MYSQL不太熟悉,所以请有人告诉我我做错了什么,或者该查询不符合标准。


这里有一些示例数据需要处理。

tbl_user([M1111,Jon,Doe,0],[M1112,Jane,Doe,1],[M1113,Jony,Doe,0])

tbl_payment([1,M1111,Monthly,2018-05-14,2018-06-14,b123,2018-05-14],[2,M1112,3Months,2018-02-03,2018-05- 03,b112,2018-02-03],[3,M1113,每月,2018-06-14,2018-07-14,b158,2018-06-14],[4,M1111,每月,2018-06- 15,2018-07-15,b345,2018-06-15],[5,M1113,每月,2018-06-06,2018-07-06,b158,2018-06-06],[6,M1111,每月,2018-07-05,2018-08-05,b345,2018-07-05])

假设当前日期为2018年7月17日,则预期结果应为

[M1111,Jon,Doe,每月,2018-06-15,2018-07-15,b345,2018-06-15],[M1113,Jony,Doe,每月,2018-06-14,2018- 07-14,b158,2018-06-14]

相反,我的查询给了我这个

[M1111,Jon,Doe,每月,2018-06-15,2018-07-15,b345,2018-06-15],[M1113,Jony,Doe,每月,2018-06-06,2018- 07-06,b158,2018-06-06], [M1113,Jony,Doe,Monthly,2018-06-14,2018-07-14,b158,2018-06-14]

2 个答案:

答案 0 :(得分:0)

我写了另一个查询,该查询完全为我提供了我想要的结果集。但我不确定是否符合标准。如果有人可以简化或改进它,请非常感谢。

SELECT A.reg_id,A.f_name,A.l_name,D.mem_plan,D.from_date,D.to_date,D.bill_no,D.payed_date
FROM tbl_user A
JOIN (SELECT B.reg_id,B.mem_plan,B.from_date,B.to_date,B.bill_no,B.payed_date
FROM tbl_payments B
JOIN (
SELECT reg_id, MAX(to_date) as to_date
FROM tbl_payments
WHERE DATE(NOW()) >= DATE(to_date) AND DATEDIFF(DATE(NOW()), DATE(to_date))<31
GROUP BY reg_id) C
ON B.reg_id = C.reg_id AND B.to_date= C.to_date) D
ON A.reg_id = D.reg_id
WHERE A.status=0;

答案 1 :(得分:0)

我相信having在这里不起作用,并且您的第二个查询与它查询的一样好。我在这里把它浓缩了一点:

 SELECT A.reg_id,f_name,l_name,mem_plan,from_date,to_date,bill_no,payed_date
 FROM @tbl_user A
 JOIN  @tbl_payments B ON A.reg_id = b.reg_id
 JOIN (
    SELECT reg_id, MAX(to_date) as max_to_date
    FROM @tbl_payments
    WHERE DATE(NOW()) >= DATE(to_date) AND DATEDIFF(DATE(NOW()), DATE(to_date))<31
    GROUP BY reg_id
 ) C ON B.reg_id = C.reg_id AND B.to_date= C.max_to_date
 WHERE A.status=0;