gpt4 book ai didi

php - 如何以最短的运行时间执行sql select查询

转载 作者:行者123 更新时间:2023-11-29 07:46:24 24 4
gpt4 key购买 nike

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

表格:

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

最佳答案

这是您的查询:

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和相关子查询。

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

关于php - 如何以最短的运行时间执行sql select查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27678184/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com