Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL: select latest record only (on left join table)

Tags:

php

mysql

I have 2 tables:

Table1:

ID | Mobile Number | Name | Ordered Product| Order Date

Table2:

ID(foreign_key can be inserted multipletimes in this table) |Contacted_for | Time(timestamp)

I need a query to display all the data in Table1 and if the ID is present in Table 2, I need to display the last inserted record on Table2(with time) of that ID

My query is

select a.* , b.* FROM table1 a LEFT JOIN table2 b ON a.ID=b.ID GROUP BY a.ID ORDER BY b.Time DESC

Here in my query when I remove Group By a.ID, it works but shows all results. But I want to show final record of table2 only(no duplicate ID records)

Thanks in advance

like image 241
Pradeep Kumar Avatar asked Jan 16 '15 08:01

Pradeep Kumar


People also ask

Does LEFT join create new rows?

Left joins can increase the number of rows in the left table if there are multiple matches in the right table.

Can we use left join in update query?

To query data from related tables, you often use the join clauses, either inner join or left join. In SQL Server, you can use these join clauses in the UPDATE statement to perform a cross-table update. In this syntax: First, specify the name of the table (t1) that you want to update in the UPDATE clause.

How do I select the last 5 records of a table?

METHOD 1 : Using LIMIT clause in descending orderof specified rows from specifies row. We will retrieve last 5 rows in descending order using LIMIT and ORDER BY clauses and finally make the resultant rows ascending. Since Employee table has IDs, we will perform ORDER BY ID in our query.

Can we use LEFT join without on condition?

Any JOIN without an ON clause is a CROSS JOIN. The LEFT JOIN is an outer join, which produces a result set with all rows from the table on the "left" (t1); the values for the columns in the other table (t2) depend on whether or not a match was found.


2 Answers

You can also try this way.

Select * from table1 a left join
(Select * from table2 where id in (select max(id) from table2 group by id) ) b on a.id=b.id
like image 173
user11069271 Avatar answered Oct 21 '22 11:10

user11069271


You'll need some subquery's for that:

SELECT
    a.*, b.*
FROM
    table1 a
LEFT JOIN
    (SELECT c.id, d.contacted_for, c.time
     FROM
         (SELECT
            id,
            MAX(time) time
         FROM
             table2
         GROUP BY id
         ) c
     JOIN
         table2 d
         ON c.id = d.id AND d.time = c.time
     ) b
     ON a.id = b.id
like image 27
Gervs Avatar answered Oct 21 '22 11:10

Gervs