SQL连接两个表尊重顺序

时间:2014-03-02 12:25:24

标签: mysql sql join

我有两张桌子。表1存储代码的位置顺序。表2存储每个代码的信息。我尝试执行一个id的查询,返回每个代码的顺序及其相关信息。

TABLE1
+-------+-----------+----------+-----------+-----------+-----------+
| id    | position1 | positon2 | position3 | position4 | position5 |
+-------+-----------+----------+-----------+-----------+-----------+
| id1   | AA        | CC       | BB        | EE        | DD        |
|-------|-----------|----------|-----------|-----------|-----------|
| id2   | BB        | AA       | DD        | EE        | CC        |
+-------+-----------+----------+-----------+-----------+-----------+

TABLE2
+------+------------+--------------------+
| code | name       | active_icon        | 
+------+------------+--------------------+
| AA   | nameA      | iconA              |
| BB   | nameB      | iconB              |
| CC   | nameC      | iconC              |
| DD   | nameD      | iconD              |
| EE   | nameE      | iconE              |
+------+------------+--------------------+

完成一个id(例如id = id2),我期待的结果是:

+----------------+------+------------+--------------------+
| position       | code | name       | active_icon        |
+----------------+------+------------+--------------------+
|              1 | BB   | nameB      | iconB              |
|              2 | AA   | nameA      | iconA              |
|              3 | DD   | nameD      | iconD              |
|              4 | EE   | nameE      | iconE              |
|              5 | CC   | nameC      | iconC              |
+----------------+------+------------+--------------------+

有什么想法吗?我认为必须有一个INNER JOIN,但我不知道如何构建它。

3 个答案:

答案 0 :(得分:0)

这是一种非规范化设计。如果你正确地建模它会更容易。它也可以扩展得更远。

我会给表1一个列位置,一个外键给表2代码。你可以拥有你想要的代码。重新排序意味着改变位置值。然后JOIN会自行编写:只需添加一个ORDER BY位置。

答案 1 :(得分:0)

SELECT position, t1.code, name, active_icon
FROM (SELECT 1 AS position, id, position1 AS code
      FROM Table1
      UNION
      SELECT 2 AS position, id, position2 AS code
      FROM Table1
      UNION
      SELECT 3 AS position, id, position3 AS code
      FROM Table1
      UNION
      SELECT 4 AS position, id, position4 AS code
      FROM Table1
      UNION
      SELECT 5 AS position, id, position5 AS code
      FROM Table1) AS t1
JOIN Table2 AS t2
ON t1.code = t2.code
WHERE t1.id = :ID
ORDER BY position

答案 2 :(得分:0)

您可以尝试使用PIVOT操作。但是在MySQL中,pivot是未经过执行的,但您可以手动模拟它。有关示例,请参阅MySQL pivot table