MySQL UNION语句慢查询

时间:2015-05-12 19:11:28

标签: mysql

是否可以进行任何优化以帮助使以下语句更快地执行,而不是标记为"慢"查询?

SELECT id FROM equipment_acc_1 WHERE nick='Cutter29'
    UNION ALL
SELECT id FROM equipment_acc_2 WHERE nick='Cutter29'
    UNION ALL
SELECT id FROM equipment_gloves WHERE nick='Cutter29'
    UNION ALL
SELECT id FROM equipment_head WHERE nick='Cutter29'
    UNION ALL
SELECT id FROM equipment_pants WHERE nick='Cutter29'
    UNION ALL
SELECT id FROM equipment_shoes WHERE nick='Cutter29'
    UNION ALL
SELECT id FROM equipment_top WHERE nick='Cutter29'
    UNION ALL
SELECT id FROM equipment_donation_skins WHERE nick='Cutter29'
    UNION ALL
SELECT id FROM equipment_weapon WHERE nick='Cutter29';

此查询中的所有表都完全相同,这是一个示例:

mysql> describe equipment_acc_1;
+----------+----------+------+-----+---------+-------+
| Field    | Type     | Null | Key | Default | Extra |
+----------+----------+------+-----+---------+-------+
| nick     | char(25) | NO   | PRI | NULL    |       |
| id       | int(11)  | NO   | MUL | NULL    |       |
| cooldown | datetime | NO   | MUL | NULL    |       |
+----------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)

提前多多感谢!

2 个答案:

答案 0 :(得分:0)

对于联合没有多少人可以做 - 但如果确保所有表中都有数据,你可以试试这个(如果数据不能保证使用外联接)

select a.id, b.id, c.id, d.id, e.id, f.id, g.id, h.id
from equipment_acc_1 a,equipment_acc_2 b, equipment_gloves c, equipment_pants d, equipment_shoes e, equipment_top f, equipment_donation_skins g, equipment_weapon h
where a.nick='Cutter29'
and b.nick=a.nick
and c.nick=a.nick
and d.nick=a.nick
and e.nick=a.nick
and f.nick=a.nick
and g.nick=a.nick
and h.nick=a.nick

答案 1 :(得分:0)

您可以更改设计并将所有小表合并为一个:

Equipment_parts:
Part_id
Equipment_id
Part_type
Part_name
Nick
...

然后你可以使用索引快速找到“cutter29”。