I have a two different tables
Table 1
id
name
description
Table 2
id
details
info
table1_id
I want to display all the records from the table1
except id
but from table2
I used to display the max id
.
eg. table1
have following records
id=1
name = test
description = some text
table2 have
id=5
details = some more text
info = the new info
table1_id = 1
so the result what I want is
id name description
5 test some text
Try this:
select
(select max(table2.id) from table2 where table1.id = table2.table1_id) id,
name,
description
from table1
or left join
:
select
t.id,
table1.name,
table1.description
from table1
left join (
select max(id) id, table1_id from table2 group by table1_id
) t on table1.id = t.table1_id
You can try with and max.
with ID_Table_1_MaxID_Table_2 as (
select table1_id, max(id) Max_Table2_ID
from Table_2
group by table1_id
)
SELECT tb2.id, tb1.name, tb1.description
FROM Table_2 tb2
INNER JOIN ID_Table_1_MaxID_Table_2 sub
ON (sub.table1_id = tb2.table1_id and tb2.id = sub.Max_Table2_ID)
INNER JOIN Table_1 tb1 on tb1.id = sub.table1_id