从两个具有id的表中检索数据,并在Mysql中显示另一个表的最大id

时间:2017-09-25 12:21:39

标签: php mysql sql

我有两个不同的表

Table 1
id
name
description

Table 2
id 
details
info
table1_id

我希望显示table1id以外的所有记录,但是来自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

2 个答案:

答案 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