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
Left joins can increase the number of rows in the left table if there are multiple matches in the right table.
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.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With