我有两张桌子:
TABLE_1 :
id | equipment |
1 | voltimeter |
2 | amperemeter |
3 | wattimeter |
4 | eletrical gloves |
TABLE_2
id | id_table1 | inspection_date
1 | 2 | 2017-01-05
1 | 2 | 2017-02-07
1 | 3 | 2017-05-09
1 | 3 | 2018-09-23
1 | 2 | 2018-05-09
1 | 2 | 2017-11-05
我想在TABLE_1上列出具有最快检验日期TABLE_2
的列的所有值结果应该是:
id | equipment | last_inspection_date
1 | voltimeter |
2 | amperemeter | 2018-05-09
3 | wattimeter | 2018-09-23
4 | eletrical gloves |
我拥有的是:
SELECT t1.*, Max(t2.inspection_date) LastInspectionDate
FROM table_1 t1
LEFT JOIN table_2 t2 ON t2.id_table1 = t1.id
我在这里做错了什么?我只得到1排:(
答案 0 :(得分:0)
您可以通过id_table1加入ond子查询组以获取最大日期
select a.equipment
from table_1 a
left join (
select id_table1, max(inspection_date)
from table_2
group by id_table1 ) t on a.id = t.id_table1
答案 1 :(得分:0)
您可以在两个查询中执行此操作:一个用于table_1,另一个子查询用于表_2中相关的最新检查日期。
select
id,
equipment,
(select max(inspection_date) from table_2 t2 where t2.id_table1 = t1.id) as last_insp
from table_1 t1
order by id;
答案 2 :(得分:0)
您只是错过了GROUP BY
条款:
SELECT t1.id, t1.equipment, MAX(t2.inspection_date) AS LastInspectionDate
FROM table_1 t1
LEFT JOIN table_2 t2 ON t2.id_table1 = t1.id
GROUP BY t1.id
ORDER BY t1.id;
(MAX
是一个聚合函数。它将所有数据聚合到一行,如果你没有指定你希望最大的列数。在你的情况下每table_1行,即每t1.id
。)