0

我有一个由多个连接组成的查询,我想知道是否可以重写它以提高性能。

我有 2 个表如下(我已删除此示例的非重要列):

插槽

------------------------------------------
| id   | name | slot_1 | slot_2 | slot_3 |
------------------------------------------
| 1    | Bob  | 1      | 2      | 3      |
| 2    | Jim  | 4      | 3      | 3      |
| 3    | Alf  | 1      | 2      | 5      |
------------------------------------------

(总共有 25 个插槽,每个插槽都有自己的列)

slot_details

-----------------------------------
| id   | stat_1 | stat_2 | stat_3 |
-----------------------------------
| 1    | 1      | 5      | 6      |
| 2    | 4      | 31     | 23     |
| 3    | 6      | 5      | 7      |
| 4    | 7      | 4      | 9      |
| 5    | 2      | 3      | 5      |
-----------------------------------

(总共有10个统计)

查询如下:

SELECT
    slots.name,
    slot_1_details.stat_1 AS slot_1_stat_1,
    slot_1_details.stat_2 AS slot_1_stat_2,
    slot_1_details.stat_3 AS slot_1_stat_3,
    slot_2_details.stat_1 AS slot_2_stat_1,
    slot_2_details.stat_2 AS slot_2_stat_2,
    slot_2_details.stat_3 AS slot_2_stat_3,
    slot_3_details.stat_1 AS slot_3_stat_1,
    slot_3_details.stat_2 AS slot_3_stat_2,
    slot_3_details.stat_3 AS slot_3_stat_3
FROM
    slots
LEFT JOIN
    slot_details AS slot_1_details
ON (
    slot_1_details.id = slots.slot_1
)
LEFT JOIN
    slot_details AS slot_2_details
ON (
    slot_2_details.id = slots.slot_2
)
LEFT JOIN
    slot_details AS slot_3_details
ON (
    slot_3_details.id = slots.slot_3
)
WHERE (
    slots.id = 1
)

此查询的预期结果如下:

| name | slot_1_stat_1 | slot_1_stat_2 | slot_1_stat_3 | slot_2_stat_1 | slot_2_stat_2 | slot_2_stat_3 | slot_3_stat_1 | slot_3_stat_2 | slot_3_stat_3 |
|bob   | 1             | 5             | 6             | 4             | 31            | 23            | 6             | 5             | 7             |

不幸的是,我无法更改表格。

感谢您的帮助!

4

1 回答 1

0

也许

SELECT * FROM slots s LEFT JOIN slot_details sd ON s.id=sd.id

但我不确定,因为您发布的查询非常混乱。

这些表的键是什么?

于 2012-10-26T13:19:08.297 回答