简体   繁体   中英

SQL query join- unrelated tables

Can someone help me to join the two tables without any primary or secondary keys. Sample table is

TABLE 1

| ID | NAME |
|  1 | x    |
|  2 | Y    |
|  3 | z    |

TABLE 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  |

I want retrieve data from 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 |

Now I will get three data from table2. I'm little stuck after this step. I want to get top of data the from table 2 and combine with table one.

I want final output should be

| ID | NAME | Num | DATE      |
| 1  | x    | 52  | 12-aug-17 |

Can someone suggest me how can I join this table? Its easy to join when we have any primary key but here not the case

Thanks

You need to get the maximum DATE using a subquery, as in:

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'
  );

You can use this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM