我该如何编写包含多个Left Joins的MySQL查询

时间:2012-10-26 13:12:10

标签: mysql performance join

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

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

------------------------------------------
| 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             |

不幸的是,我不能改变表格。

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

也许

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

但我不确定,因为您发布的查询非常令人困惑。

这些表的关键是什么?