我有两个不同的表
Table 1
id
name
description
Table 2
id
details
info
table1_id
我希望显示table1
除id
以外的所有记录,但是来自table2
我用来显示最大id
的记录。
例如。 table1
有以下记录
id=1
name = test
description = some text
table2 have
id=5
details = some more text
info = the new info
table1_id = 1
所以我想要的结果是
id name description
5 test some text
答案 0 :(得分:1)
试试这个:
select
(select max(table2.id) from table2 where table1.id = table2.table1_id) id,
name,
description
from table1
或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
答案 1 :(得分:0)
您可以尝试使用和最大
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