1

我有一张这样的桌子:

idstable
+--------+-----+-----+-----+-----+-----+
| userid | id1 | id2 | id3 | id4 | id5 |
+--------+-----+-----+-----+-----+-----+
|   1    |  6  |  2  |  52 |  32 |  16 |
+--------+-----+-----+-----+-----+-----+
|   2    |  12 |  5  |  18 |  21 |  5  |
+--------+-----+-----+-----+-----+-----+
|  ...   | ... | ... | ... | ... | ... |

我想获取存储在列中的 id 号并从另一个表中获取行。我希望从中获取行的表是:

namestable
+----+----------+
| id |   name   |
+----+----------+
| 6  |   Bruce  |
+----+----------+
| 2  |   Mary   |
+----+----------+
| 52 |   Dick   |
+----+----------+
| 32 |   Bob    |
+----+----------+
| 16 |   Jack   |
+----+----------+
| .. |   ...    |

我试图得到的结果集是这样的:

+------+----+-------+
| User | id | name  |
+------+----+-------+
| 1    | 6  | Bruce |
+------+----+-------+
| 1    | 2  | Mary  |
+------+----+-------+
| 1    | 52 | Dick  |
+------+----+-------+
| 1    | 32 | Bob   |
+------+----+-------+
| 1    | 16 | Jack  |
+------+----+-------+

如何使用用户 ID 查询idstable以检索与其关联的 ID,然后从中检索正确的行namestable?我读过这叫做转置,但我还没有找到一个简洁的例子。

有任何想法吗?

4

1 回答 1

1

join

SELECT idstable.id as User, namestable.id as id, namestable.name as name
FROM idstable it
JOIN namestable nt on (nt.id = it.id1 or nt.id = it.id2 ... 3,4,5 like the first two)

理想情况下,您的 idstable 不会有 5 列,而是每个 id 有 5 行。

于 2011-02-22T18:15:42.547 回答