【问题标题】:how to execute sql select query with minimum runtime如何以最少的运行时间执行 sql 选择查询
【发布时间】:2015-02-25 00:12:26
【问题描述】:

我想从一个表中进行选择,然后为每个表进行选择。

表格:

category
+====+=======+
| id | title |
+====+=======+
this table has list of category

email
+====+=======+==========+=============+
| id | eMail | domainId | elseColumns |
+====+=======+==========+=============+
this table has list of emails but domains are in another table

domain
+====+========+=============+
| id | domain | elseColumns |
+====+========+=============+
list of domains which used in email

subscriber_category
+========+============+
| userId | categoryId |
+========+============+
list of emails in categories

现在的问题是我如何以最少的运行时间列出类别和其中的电子邮件数量?我的尝试是等待 20 秒等待 200000 封电子邮件和 20 个类别。

sql:

SELECT category.*,
(SELECT COUNT(DISTINCT subscriber_category.userId) FROM subscriber_category
    JOIN email ON email.id=subscriber_category.userId
    JOIN domain ON domain.id=email.domainId
WHERE subscriber_category.categoryId=category.id
    AND email.blackList=0
    AND domain.blackList=0
) AS qty
FROM category WHERE category.userId=1 ORDER BY category.title ASC

【问题讨论】:

    标签: php mysql sql normalization database-normalization


    【解决方案1】:

    这是您的查询:

    SELECT c.*,
           (SELECT COUNT(DISTINCT sc.userId)
            FROM subscriber_category sc JOIN
                 email e
                 ON e.id = sc.userId JOIN
                 domain d
                 ON d.id = e.domainId
           WHERE sc.categoryId = c.id AND e.blackList = 0 AND d.blackList = 0
          ) AS qty
    FROM category c
    WHERE c.userId = 1
    ORDER BY c.title ASC;
    

    结构相当合理,索引应该有助于性能。第一个索引位于category(userId, title, id)。此索引应该用于WHERE 子句、ORDER BY 和相关子查询。

    接下来,我假设您在emaildomainid 列上有索引。如果您将blacklist 标志作为索引中的第二列包括在内,则可以使这些稍微更适用于查询。更重要的是,您需要在subscriber_category(categoryId, userId) 上建立索引。如果没有必要,我还建议删除count(distinct)

    【讨论】:

    • 我的上帝!!!!你的记录是1.0499sec。正如你所说,我改变了索引。如果我设置表之间的关系,是否会受到尊重?
    • @Pooya 。 . .我不明白您评论中的问题。
    • 我想知道如果我设置表的外键有帮助吗?即:email.domainId to domain.id
    • @Pooya 。 . .外键不直接影响性能,除了一种间接方式:它们要求引用表中的列是主键或唯一的,因此它们上有一个索引。在这种情况下这无济于事。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-03
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 2016-01-29
    相关资源
    最近更新 更多