以下是我的示例表,我需要帮助我如何正确检索它们。
Table_1 Table_2
| Im_ID | Im_Name | | Im_ID | S_Im_ID |
| 001 | ABC | | 001 | 004 |
| 002 | XYZ | | 002 | 005 |
| 003 | PQR | | 003 | 006 |
| 004 | STU |
| 005 | DEF |
| 006 | JKL |
我想要这样的结果:
Result
| Im_ID | S_Im_ID | Im_Name | S_Im_Name |
| 001 | 004 | ABC | STU |
| 002 | 005 | XYZ | DEF |
| 003 | 006 | PQR | JKL |
我无法理解如何获取im_id和s_im_id的名称。我只能为其中一个做这件事。
答案 0 :(得分:1)
这需要使用联结表JOIN
进行两次Table_2
操作,以便将Table_1
加入自身:
SELECT t1.Im_ID, t3.Im_ID AS S_Im_ID, t1.Im_Name, t3.Im_Name AS S_Im_Name
FROM Table_1 AS t1
INNER JOIN Table_2 AS t2 ON t1.Im_ID = t2.Im_ID
INNER JOIN Table_1 AS t3 ON t2.S_Im_ID = t3.Im_ID