Mysql join table - select a new row

I have the following two MySQL tables

TABLE TITLES

NAME_ID   NAME
1         name1
2         name2
3         name3

TABLE OF CONDITION

STATUS_ID    NAME_ID     TIMESTAMP
1            1           2010-12-20 12:00
2            2           2010-12-20 10:00
3            3           2010-12-20 10:30
4            3           2010-12-20 14:00

I would like to select all the information from the TITLE table and add the last TIMESTAMP column from the STATUS table

RESULT

NAME_ID NAME     TIMESTAMP
1       name1    2010-12-20 12:00
2       name2    2010-12-20 10:00
3       name3    2010-12-20 14:00

I am stuck on this. How do I leave a connection in a new timestamp only?

+3
source share
3 answers

try this query:

select n.NAME_ID ,  n.NAME , max(TIMESTAMP) as time from NAMES n left join 
STATUS s on s.NAME_ID = n.NAME_ID group by n.NAME_ID
+2
source
SELECT  *
FROM    table_names tn
LEFT JOIN
        table_status ts
ON      ts.status_id = 
        (
        SELECT  status_id
        FROM    table_status tsi
        WHERE   tsi.name_id = tn.name_id
        ORDER BY
                name_id DESC, TIMESTAMP DESC, status_id DESC
        LIMIT 1
        )

This will allow duplicates to be processed correctly.

Create an index on table_status (name_id, timestamp, status_id)to make it work fast.

+2
source
SELECT
    status.*
FROM
    status
        JOIN
            (SELECT name_id, MAX(timestamp)AS latest FROM status GROUP BY name_id) AS sub 
            ON (status.name_id = sub.name_id AND status.timestamp = sub.latest);
0

Source: https://habr.com/ru/post/1781458/


All Articles