mysql - MySQL 中的高效子查询

标签 mysql sql database performance

我对 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/

相关文章:

java - SQL更新查询-尝试更新sql记录

mysql - 为 Ruby 安装 MySQL2 适配器

sql - 同一 View 上具有不同条件的两个计数查询

java - Android SQLite 游标错误

sql - Azure SQL 查看辅助(异地复制)数据库的内容

php - 如何将 Controller 变量传递给 CakePHP 中的 View ?

mysqldump 未知数据库 bitnami_redmine

Mysql在删除集null时创建具有多个外键的表

java - 如何在 java 中使用 PreparedStatement 在 mySql 数据库中插入日期时间字段?

mysql - 消息 2627 违反 PRIMARY KEY 约束