mysql - 哪些索引应该有一个表来快速执行大型 SQL 查询?

标签 mysql sql indexing

我有一个表,里面的数据是快速流转的。这是它的结构:

CREATE TABLE `tasks_pending` (
  `pending_id` int(11) NOT NULL AUTO_INCREMENT,
  `task_id` int(9) NOT NULL,
  `user_id` int(9) NOT NULL,
  `added_time` int(11) NOT NULL DEFAULT '0',
  `additional` varchar(1000) DEFAULT NULL,
  `taken` tinyint(1) NOT NULL DEFAULT '0',
  `taken_by` int(11) NOT NULL,
  `taken_time` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`pending_id`),
  UNIQUE KEY `task_id` (`task_id`,`user_id`),
  KEY `user_id` (`user_id`),
  KEY `added_time` (`added_time`),
  KEY `task_id_2` (`task_id`),
  KEY `taken` (`taken`)
) ENGINE=MEMORY

我还有一个大查询可以提取所需的数据:

SELECT DISTINCT `task_id` AS tid, `pending_id` as pid, `taken_time`, `taken_by`,  `additional`, 
(
    SELECT COUNT( pending_id ) 
    FROM tasks_pending tp
    WHERE task_id = tid
) AS count, 
(
    SELECT remain
    FROM tasks
    WHERE task_id = tid
) AS rem, 
(
    SELECT type 
    FROM tasks tas
    WHERE task_id = tid
) AS type 
FROM  `tasks_pending` 
WHERE  `taken` =  '0'
HAVING 
(
    count > 9
    OR count = rem
    OR type =  'pack'
)
limit 30

子查询的where子句中的所有列都有PRIMARY索引,所以它们必须快速执行。 我找不到问题,也许你能找到我吗?提前谢谢你。

附言我是俄罗斯人,很抱歉英语不好。

UPD:tasks 表的结构:

CREATE TABLE `tasks` (
  `task_id` int(50) NOT NULL AUTO_INCREMENT,
  `user_id` int(50) DEFAULT NULL,
  `type` enum('video','friend','group','like','pack','other') NOT NULL,
  `url` varchar(500) NOT NULL,
  `additional` varchar(1000) DEFAULT NULL,
  `remain` int(30) DEFAULT NULL,
  `created_at` int(11) NOT NULL DEFAULT '0',
  `updated_at` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`task_id`),
  KEY `user_id` (`user_id`),
  KEY `remain` (`remain`),
  KEY `created_at` (`created_at`),
  KEY `updated_at` (`updated_at`)
) ENGINE=InnoDB 

最佳答案

您可以尝试使用 GROUP BY 子句并删除您的子选择来简化您的查询。这可以提高性能。试试这个:

SELECT  t.task_id, COUNT(pending_id) count, taken_time, taken_by, type, remain

FROM    tasks_pending tp

        JOIN tasks t ON tp.task_id = t.tid

WHERE   taken = 0

GROUP BY task_id

HAVING  count > 9
        OR count = remain
        OR type =  'pack'

limit 30

关于mysql - 哪些索引应该有一个表来快速执行大型 SQL 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19305240/

相关文章:

mysql - INNER JOIN 组合 2 列

sql - 在多个查询中使用 postgres CTE

php - 单击过滤器按钮值重置后

ravendb - 转换结果

php - 如何准确验证数据库中的电话号码?

php - 我如何使用 SQL 和 PHP 更新这些表条目?

php - mysql 条件查询

sql - 教义 : Use dash in field alias

sql - Postgres - 理解索引

java - elasticsearch自定义相似度插件如何实现?