使用多连接进行数据库搜索

时间:2013-04-29 06:37:50

标签: mysql database join

我有一个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%

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

1 个答案:

答案 0 :(得分:1)

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

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

fix records_label

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

修复records_types

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%'这样的东西,那么%%会杀死任何类型的表现,那么你可以创建下面的索引

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

它可以进一步改善,但随着这些变化我相信你实现了你想要的。 ; - )