0

我有一个 MySQL 数据库,我想执行更大的搜索。
我在其中一张表中有大约 10k 条记录,预计会增长,但速度很慢。
最大的问题是,要执行搜索,我必须使用 4 个 JOINS 进行查询,我认为这会导致搜索速度变慢。
所以这里有一些示例结构:

[table records]
id INT unsigned PRIMARY KEY auto_increment
description text
label INT unsigned
type INT unsigned
price DECIMAL

[table records_labels]
id INT unsigned PRIMARY KEY auto_increment
label varchar

[table records_types]
id INT unsigned PRIMARY KEY auto_increment
type varchar

[table records_serial]
id INT unsigned PRIMARY KEY auto_increment
serial varchar
record INT unsigned

[table records_barcode]
id INT unsigned PRIMARY KEY auto_increment
barcode varchar
record INT unsigned

所以事情是这样运行的:
我运行一个选择的查询records.id, records.description, records.price, records_labels.label, records_types.type, records_serial.serial, records_barcode.barcode; 所以完整的查询是这样的:

SELECT records.id, records.description, records.price, records_labels.label, records_types.type, records_serial.serial, records_barcode.barcode FROM records JOIN records_labels ON records_labels.id = records.label JOIN records_types ON records_types.id = records.type LEFT JOIN records_serial ON records_serial.record = record.id LEFT JOIN records_barcode ON records_barcode.record = record.id WHERE records_serial.serial LIKE %SEARCH_TERM% OR records_barcode.barcode LIKE %SEARCH_TERM%

我认为这里的解决方案是索引,但我对它不是很熟悉。
那么很快,如何加速和优化这种查询呢?

4

1 回答 1

1

索引记录(可选,但推荐)

CREATE INDEX ilabel ON records (`label`);
CREATE INDEX itype ON records (`type`);

修复records_label

ALTER TABLE records_label MODIFY label INT(10) UNSIGNED NULL;
CREATE INDEX ilabel ON records_label (`label`);

修复记录类型

ALTER TABLE records_types MODIFY `type` INT(10) UNSIGNED NULL;
CREATE INDEX itype ON records_types (`type`);

搜索

SELECT r.id, r.description, r.price, rl.label, 
    rt.`type`, records_serial.`serial`, records_barcode.barcode 
FROM records r
INNER JOIN records_labels rl ON rl.id = r.label 
INNER JOIN records_types rt ON rt.id = r.`type` 
WHERE 
    r.id IN (
        SELECT rs.record
        FROM records_serial rs
        WHERE rs.`serial` LIKE '%SEARCH_TERM%' 
    )
    OR 
    r.id IN (
        SELECT rb.record
        FROM records_barcode rb
        WHERE rb.barcode LIKE '%SEARCH_TERM%'
    );

对于您的 where 子句,我无能为力。如果您热衷于将其更改为 LIKE 'SEARCH_TERM%' 之类的内容,Like %% 会杀死任何类型的性能,那么您可以在下面创建索引

CREATE INDEX iserial ON records_serial (`serial`(10));
CREATE INDEX ibarcode ON records_barcode (`barcode`(10));

它可以进一步改进,但通过这些变化,我相信你会实现你想要的。;-)

于 2013-04-29T10:33:41.447 回答