Mysql查询优化

发布于 2024-08-23 12:30:07 字数 588 浏览 7 评论 0原文

查询1:

SELECT  cid,
        dl
FROM    chal
WHERE   cid IN (
        SELECT  cid
        FROM    c_users
        WHERE   uid = 636587
        );

查询2:

SELECT  chal.cid AS cid,
        chal.dl  AS dl
FROM    chal,
        c_users
WHERE   uid = 808
        AND    chal.cid = c_users.cid;

cid是chal中的主键 cid和uid在c_users中索引,cid不唯一;

上述查询哪个更好?

解释如下

  • 查询1使用两种类型的索引,即ALL和index_subquery

  • 查询2使用两种类型的索引,即ALL和ref

    >

我想知道为什么两个查询都将 ALL 作为索引类型,尽管 cid 是表 chal 中的主键。

Query 1:

SELECT  cid,
        dl
FROM    chal
WHERE   cid IN (
        SELECT  cid
        FROM    c_users
        WHERE   uid = 636587
        );

Query 2:

SELECT  chal.cid AS cid,
        chal.dl  AS dl
FROM    chal,
        c_users
WHERE   uid = 808
        AND    chal.cid = c_users.cid;

cid is primary key in chal
cid and uid are indexed in c_users, cid is not unique;

Which of the above query is better?

Explain says the following

  • Query 1 uses two types of index namely ALL and index_subquery

  • Query 2 users two types of index namely ALL and ref

I wonder why both queries say ALL as type of index though cid is primary key in table chal.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一个人的旅程 2024-08-30 12:30:07

cid 是否已在 c_users 中建立索引?如果不是,则保证在这里进行全表扫描(又名“ALL”)。

Is cid indexed in c_users? If it's not, you're guaranteed a full table scan (aka "ALL") here.

ㄖ落Θ余辉 2024-08-30 12:30:07

我假设您问哪个查询会更快,那么根据经验,第二个查询会更快。但对于行数较少的表来说,差异并不显着。

I assume you are asking which query will be faster, then as a rule of thumb, the second query will be faster. But the difference will be insignificant for tables with a small number of rows.

£烟消云散 2024-08-30 12:30:07

我不会使用联接或嵌套选择。

我会在应用程序级别编写两条sql,随着规模的扩大,速度会快得多。

并且您的选择应该基于两个表上的主键。即cid

I wouldn't use joins or nested select.

I would write two sql at the application level which will be much faster as you scale.

and your select should be based on primary key on the both the tables. i.e cid

皇甫轩 2024-08-30 12:30:07

这些查询并不相同。

如果 c_users 中给定用户有 2 个相等的 cid,则第一个查询将为每个 cid 返回 1 条记录>,而第二个将返回两条记录。

index_subqueryMySQL 中的优化,它将用 IN 测试的表达式推入 IN 子查询并返回 第一场比赛为 TRUE

第一个查询将始终使用 chal 作为主表,而第二个查询可以在 chalc_users 之间选择,并且很可能会选择 c_users

您应该在 c_users (uid, cid) 上创建复合索引。

These queries are not identical.

If there are 2 equal cids for a given user in c_users, the first query will return 1 record per cid, while the second one will return two records.

index_subquery is the optimization in MySQL that pushes the expression tested with IN into the IN subquery and returns TRUE on the first match.

The first query will always use chal as a leading table, while the second one can choose betwee chal and c_users and most probably will choose c_users.

You should create a composite index on c_users (uid, cid).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文