Tablename: call
-------------------
|id | name |
-------------------
| 1 | a |
| 2 | b |
| 3 | c |
| 4 | d |
| 5 | e |
-------------------
Tablename: call_detail
--------------------------------
|id | detail | call_id |
--------------------------------
|1 | note-1 | 1 |
|2 | note-2 | 1 |
|3 | note-3 | 2 |
|4 | note-4 | 2 |
|5 | note-5 | 2 |
|6 | note-6 | 3 |
--------------------------------
需要结果
----------------------
| id | name | detail |
| 1 | a | note-2 |
| 2 | b | note-5 |
| 3 | c | note-6 |
| 4 | d | null |
| 5 | e | null |
----------------------
如何离开两个表的最后插入ID
我需要左联接call.id = call_detail.call.id最后一条记录
有没有办法做到这一点
您可以显示一个简单的样本
答案 0 :(得分:1)
使用对call_detail表的查询而不是对整个表进行查询的联接,因为在进行联接之前您需要在表中进行过滤才能正确过滤表。 您需要使用左联接来完成它。
使用以下查询:
SELECT c.id, c.name, cd.detail
FROM calls c LEFT JOIN
(SELECT
call_id,
MAX(id),
detail
FROM call_detail GROUP BY call_id) cd ON cd.call_id = c.id
您可以在这里看到它的工作:SQL Fiddle
注意:由于使用了关键字,我使用名称调用代替了调用。
答案 1 :(得分:0)
您需要进行子查询并将其用作虚拟表。 像这样:
SELECT call.id, call.name, call_detail.detail
FROM call,
LEFT JOIN ( select call_id, max(id) as last_call_id from call_detail group by call_id ) call_history ON call.id = call_history.call_id
LEFT JOIN call_detail ON call_history.last_call_id = call_detail.id
编辑:我添加了左联接:)