account
act_id | act_name | grp_id | grp_id_2
2 | test | 4 | 10
promotion
pml_id | act_id | grp_id
2 | 2 | null
3 | null | 4
4 | null | 10
我有两个表格,如上所示(已修剪)。帐号约15000条记录,促销约20000条。
客户基本上想要它,以便他们可以搜索帐户名,例如“测试”。它将显示促销事件 2、3 和 4。
会显示促销 3,因为帐户“test”的 grp_id = 4。
将显示促销 4,因为帐户“test”的 grp_id_2 = 10。
我最初是通过几次连接来做到这一点的
SELECT pml_id FROM promotion
LEFT JOIN account AS account1 ON promotion.act_id = account1.act_id
LEFT JOIN account AS account2 ON promotion.grp_id = account2.grp_id
LEFT JOIN account AS account3 ON promotion.grp_id = account3.grp_id_2
WHERE account1.act_name LIKE 'test%' or account2.act_name LIKE 'test%'
or account3.act_name LIKE 'test%'
GROUP BY pml_id
问题在于,当我开始必须加入帐户表 5 次时,这最终花费了很长时间。它还给了我大约 10000000 条记录(没有分组依据)。大多数促销事件都使用 grp_id,很少使用 act_id。
在这种情况下有没有办法快速搜索act_name列?不需要做那么多连接?
我在 act_id、pml_id、grp_id、grp_id_2 上有单个索引
注意:这是查询的一部分,用户不能按帐户进行搜索。即 where 子句可能并不总是存在
最佳答案
使用 INNER JOIN
来避免扫描整个表:
SELECT p.pml_id
FROM account a
INNER JOIN promotion p
ON (p.act_id = a.act_id OR p.grp_id = a.grp_id OR p.grp_id = a.grp_id_2)
WHERE a.act_name LIKE "test%";
关于MYSql搜索性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18777633/