2017-09-25 90 views
0

顯示另一個表的最大ID我有兩個不同的表檢索ID爲兩個表中的數據,並在MySQL

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 

回答

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 
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 
相關問題