我对 MySQL 绝对不是特别熟练,但直到现在我还不必如此。我正在处理一个大型数据库,特别是一个包含 1500 多行的用户表。因此,我需要弄清楚如何有效地完成我使用 IN 子句完成的任务。
这是查询:
SELECT *
FROM artists_profile
WHERE artist_name LIKE '%$test%' OR id IN (SELECT profile_id
FROM artists_profileltp_join
WHERE genre_id IN (SELECT id
FROM artists_ltp
WHERE genre LIKE '%$test%') OR
details LIKE '%$test%')
包含示例数据的数据库
artists_profile artists_profileltp_join
+------+-------------+ +---------+------------+---------+
| ID | artist_name | |genre_id | profile_id | details |
+------+-------------+ +---------+------------+---------+
| 1 | Jake | | 1 | 2 | rap |
| 2 | Obama | | 2 | 3 | smooth |
| 3 | Bob | | 1 | 1 | metal |
+------+-------------+ +---------+------------+---------+
artists_ltp
+------+-------+
| ID | genre |
+------+-------+
| 1 | rock |
| 2 | jazz |
+------+-------+
$test = "ja"的预期结果将返回 Artist_profile ID 1 和 3,因为 Jake 以“ja”开头,而 Bob 演奏的流派包含“ja”。
表格非常简单。
Artists_profile 包含有关用户的所有唯一信息。 Artists_profileltp_join 具有 profile_id (int(11))、genre_id (int(11)) 和details (varchar(200)) 字段,并且只需将artists_profile 表连接到artists_ltp 表。
artists_ltp 仅具有唯一的 ID 和 varchar(50) 字段。运行我的查询平均需要 30 秒。我可以做什么来加快速度并使子查询更加高效?
最佳答案
SELECT DISTINCT a.*
FROM artist_profile a
INNER JOIN artists_profileltp b
ON a.ID = b.profile_ID
INNER JOIN artists_ltp c
ON b.genre_id = c.id
WHERE c.genre LIKE '%$test%' OR
c.details LIKE '%$test%'
JOIN
在这方面会更好。但不幸的是,您的查询不会使用 INDEX
,因为您使用的是 LIKE
。我建议您阅读一些有关全文搜索
还有一点,该查询容易受到SQL注入(inject)
的攻击,请阅读下面的文章以了解如何防止它,
关于mysql - MySQL 中的高效子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13925833/