Last record of fields that have the same date MYSQL

3

I have the following MySQL query:

select * from venta as v, pago_venta as pv
where pv.pv_fecha in (SELECT MAX(pv_fecha) FROM pago_venta as p GROUP BY ven_id ) AND v.ven_id = pv.ven_id AND v.ven_cliente= 'Amaia Valentina Cardenas Gonzales'

This query shows the following result:

Now the problem that I can not solve is that I show the last record of each ven_id , when they have pv_fecha different dates this query works fine without problems, but if pv_fecha have the same date shows me the amount of records that are stored on the same date if 10 shows 10 of the same date. Here you can see my query: Query BD

    
asked by M.Antonio 22.08.2017 в 17:24
source

2 answers

2

A way to recover the last record of pago_venta by ven_id if we can consider (I understand that yes) that pv_id has a correlation with the date, that is the maximum pv_id is the last chronologically, it is Do the following:

SELECT pv.*
    FROM venta as v
    INNER JOIN (SELECT  VEN_ID, 
                        MAX(pv_id) as pv_id
                    FROM pago_venta
                    GROUP BY ven_id
               ) as m
        ON v.ven_id = m.ven_id 
    INNER JOIN pago_venta as pv
        ON v.ven_id = pv.ven_id 
        AND pv.pv_id = m.pv_id
    WHERE v.ven_cliente= 'Amaia Valentina Cardenas Gonzales' 

Note: I modified your JOINS to the explicit form because it is easier for me to understand and it is also the recommended form ( See ).

    
answered by 22.08.2017 / 23:43
source
1

Based on the structure of your tables, I would say that a query like this would solve your problems:

select *
from venta as v, pago_venta as pv
where 
     v.ven_id = pv.ven_id 
     AND 
     v.ven_cliente= 'Amaia Valentina Cardenas Gonzales'
     AND pv.pv_id in 
         (SELECT MAX(pv_id) FROM pago_venta as p 
          WHERE
              pv.pv_fecha in (SELECT MAX(pv_fecha) FROM pago_venta as p GROUP BY ven_id )
          GROUP BY ven_id  )

In this case I put one grouping into another as an exclusion clause. I do not think it's the most optimal (it depends a lot on the amount of data) but it returns what corresponds.

    
answered by 22.08.2017 в 21:12