SQL - 使用从同一个表中提取的另一个值来查询和替换列值

时间:2014-07-14 09:33:47

标签: sql

我有一个包含以下列的表:

ID  |  NAME  | ID_PREVIOUS  | ID_FOLLOWING |   RANDOM_USELESS_DATA
----+--------+--------------+--------------+---------------------
1   | AB2-F  |     NULL     |     2        |      bla bla bla
2   | PP-01  |      1       |     3        |      ffwfwqafrwf
3   | 10J6U  |      2       |     7        |      ihjfoiwhfo
7   | F-1-R  |      3       |   NULL       |      fdojshflos

此表代表一种图表。每一行都是一个节点,其id,名称,前一节点和后一节点的id以及一些对该问题无用的其他数据。请注意,adiacent节点可以为null,这意味着特定节点只有一个连接。

我不能做的是创建一个用相应的节点名替换所有ID的查询。我需要代表"图表"有名字,但我不知道该怎么做。我理想的结果是:

NAME  |  NAME_PREVIOUS |   NAME_FOLLOWING
------+----------------+------------------
AB2-F |    NULL        |  PP-01
PP-01 |    AB2-F       |  10J6U
10J6U |    PP-01       |  F-1-R
F-1-R |    10J6U       |  NULL

感谢您的帮助。

4 个答案:

答案 0 :(得分:1)

SELECT T.NAME, 
TP.NAME AS NAME_PREVIOUS,
TF.NAME AS NAME_FOLLOWING
FROM YOUR_TABLE AS T
LEFT JOIN YOUR_TABLE AS TP TP.ID = T.ID_PREVIOUS 
LEFT JOIN YOUR_TABLE AS TF TF.ID = T.ID_FOLLOWING

这是我认为应该适用于大多数DBMS的通用SQL,但是我知道Access查询构建器由于某些原因也会在FROM子句中添加括号,如下所示:

SELECT T.NAME, 
TP.NAME AS NAME_PREVIOUS,
TF.NAME AS NAME_FOLLOWING
FROM (YOUR_TABLE AS T
LEFT JOIN YOUR_TABLE AS TP TP.ID = T.ID_PREVIOUS) 
LEFT JOIN YOUR_TABLE AS TF TF.ID = T.ID_FOLLOWING

答案 1 :(得分:1)

如果您只有一个级别的"之前/之后"你可以通过自我加入来逃脱

select nd.name, 
       pr.name as name_previous,
       nx.name as name_following
from nodes nd 
  left join nodes pr on nd.id_previous = pr.id
  left join nodes nx on nd.id_following = nx.id;

SQLFiddle:http://sqlfiddle.com/#!15/21b46/2

如果您有多个级别,则需要递归查询(MS-Access或MySQL不支持)

答案 2 :(得分:1)

SELECT  a.NAME as NAME, b.NAME as NAME_PREVIOUS, c.NAME as NAME_FOLLOWING
FROM GRAPH_TABLE a LEFT JOIN GRAPH_TABLE b on a.ID_PREVIOUS=b.ID
LEFT JOIN GRAPH_TABLE c on a.ID_FOLLOWING=c.ID.

您可以在此处查看示例:http://sqlfiddle.com/#!2/c73c4/3

答案 3 :(得分:0)

UPDATE table T
SET T.NAME_PREVIOUS = (SELECT NAME FROM table WHERE ID = T.ID_PREVIOUS),
T.NAME_FOLLOWING = (SELECT NAME FROM table WHERE ID = T.ID_FOLLOWING);