有人可以在没有任何主键或辅助键的情况下帮助我将两个表连接起来吗?样本表是
表1
| ID | NAME |
| 1 | x |
| 2 | Y |
| 3 | z |
表2
| Num | NAME | DATE |
| 52 | X | 12-aug-17 |
| 53 | X | 11-apr-17 |
| 62 | X | 10-aug-11 |
| 12 | y | 2-jan-16 |
| 23 | Y | 3-apr-18 |
我要从X检索数据
select *
from table2
where name = 'x';
| Num | NAME | DATE |
| 52 | X | 12-aug-17 |
| 53 | X | 11-apr-17 |
| 62 | X | 10-aug-11 |
现在,我将从table2中获得三个数据。在执行此步骤后,我有点受困。我想从表2获取数据的顶部并与表1结合。
我希望最终输出应该是
| ID | NAME | Num | DATE |
| 1 | x | 52 | 12-aug-17 |
有人可以建议我如何加入此桌吗?当我们有任何主键但不是这种情况时,它很容易加入
谢谢
答案 0 :(得分:0)
您需要使用子查询来获得最大的DATE
,如:
select t1.id, t2.*
from table1 t1
join table2 t2 on t2.name = t1.name
where t2.date = (
select max(date) from table2 where name = 'x'
);
答案 1 :(得分:0)
您可以使用此:
SELECT TOP(1) table1.ID, table2.Num, table2.Name, table2.DATE
FROM table2 INNER JOIN table1 ON table1.NAME = table2.NAME
WHERE table2.NAME = 'x'
ORDER BY table2.DATE ASC
OR
SELECT table1.ID, table2.Num, table2.Name, table2.DATE
FROM table1 INNER JOIN
(SELECT TOP(1) * FROM table2 WHERE NAME = 'x' ORDER BY DATE ASC) table2
ON table1.NAME = table2.NAME