【发布时间】:2018-12-10 01:08:18
【问题描述】:
我有以下左外连接查询:
SELECT table_left.pk_id, table_left.name
FROM table_left left outer join table_right on table_right.fk_id = table_left.pk_id
WHERE table_right.name like '%entered search value%'
我遇到的问题是 table_right 有超过 1,000,000 行和超过 60 列。该查询大约需要 1 分钟,我认为这是因为它正在对所有列进行完全外部连接。我不需要所有的列。我只需要使用一列(table_right.fk_id),这样我就可以在 WHERE 子句中加入这两个表和另一列(table_right.name)。
我使用外连接是因为我需要在 table_left 中包含 table_right 中没有行的结果。
任何有助于提高上述查询速度的建议将不胜感激。
这是我拥有的两个表的示例:
+-------------------+
| table_left |
+-------------------+
| pk_id | name |
+-------+-----------+
| 1 | IBM |
+-------+-----------+
| 2 | Facebook |
+-------+-----------+
| 3 | Google |
+-------+-----------+
| 4 | Microsoft |
+-------+-----------+
+--------------------------------------------+
| table_right |
+--------------------------------------------+
| table_right_pk_id | fk_id | job_details |
+-------------------+-------+----------------+
| 1 | 1 | Tester |
+-------------------+-------+----------------+
| 2 | 2 | Toilet Cleaner |
+-------------------+-------+----------------+
| 3 | 2 | Secretary |
+-------------------+-------+----------------+
| 4 | 3 | Developer |
+-------------------+-------+----------------+
我希望能够搜索“名称”(在 table_left 中)和“job_details”(在 table_right 中),但使用 table_left 列。这是我提出的查询,查询下方是一些预期结果:
SELECT table_left.pk_id, table_left.name
FROM table_left left outer join table_right on table_right.fk_id = table_left.pk_id
WHERE table_right.name LIKE '%searchTerm%' OR table_left.name LIKE '%searchTerm%'
示例 1
searchTerm = 'IBM'
结果:
+-------------------+
| result |
+-------------------+
| pk_id | name |
+-------+-----------+
| 1 | IBM |
+-------+-----------+
示例 2
searchTerm = '测试者'
结果:
+-------------------+
| result |
+-------------------+
| pk_id | name |
+-------+-----------+
| 1 | IBM |
+-------+-----------+
示例 3
searchTerm = '微软'
结果:(即使 table_right 中没有记录,仍应返回 Microsoft)
+-------------------+
| result |
+-------------------+
| pk_id | name |
+-------+-----------+
| 4 | Microsoft |
+-------+-----------+
示例 4
searchTerm = '开发者'
结果:
+-------------------+
| result |
+-------------------+
| pk_id | name |
+-------+-----------+
| 2 | Facebook |
+-------+-----------+
【问题讨论】:
-
尝试使用
explainsql 来检查扫描了多少行以及使用了哪个索引。并且前置%并不快。无论如何,主要不是因为列太多。 -
查询正确的表时是否使用了索引?
-
我不明白你为什么在这里使用左连接的说法。不是说这是错误的,我只是不明白 “我需要在 table_left 中包含 table_right 中没有行的结果” - 左连接不会完全做到这一点。左连接只是连接来自
table_left的行,但如果不存在来自table_right的结果仍将包括在内。您能否包括架构、示例数据和预期输出?确保在两个表上都有一个关于pk_id的索引——可能是name和pk_id上的一个复合索引。我们确实需要查看更多数据才能正确回答这个问题。 -
我添加了 2 个示例表、我的查询和预期结果。我希望这会有所帮助。
标签: mysql