Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 邮箱视图,如Facebook,在分组之前按订单_Mysql_Sql_Performance - Fatal编程技术网

Mysql 邮箱视图,如Facebook,在分组之前按订单

Mysql 邮箱视图,如Facebook,在分组之前按订单,mysql,sql,performance,Mysql,Sql,Performance,我正在为我的查询寻找解决方案,以提高性能 我刚刚读了几篇关于这方面的文章,但(可能是因为我的原因)它们不适合我的情况。 无论如何,这是我的问题 我有一个类似于msg的表格: SELECT b.* FROM boxmsg b JOIN ( SELECT thread, MAX(idmsg) as idmsg FROM boxmsg x GROUP BY thread ) a ON a.thread = b.thread AND a.idmsg = b.idm

我正在为我的查询寻找解决方案,以提高性能

我刚刚读了几篇关于这方面的文章,但(可能是因为我的原因)它们不适合我的情况。 无论如何,这是我的问题

我有一个类似于msg的表格:

SELECT b.*
FROM boxmsg b
JOIN (
    SELECT thread, MAX(idmsg) as idmsg
    FROM boxmsg x
    GROUP BY thread
) a
    ON a.thread = b.thread
   AND a.idmsg  = b.idmsg

IDMSG |线程|发送方|接收方|日期| MSG |读取

1521 | 2 | 20 | 43 | 05/24/2014 |大家好| 0

1522 | 3 | 84 | 43 | 05/24/2014 |你好| 0

1523 | 2 | 20 | 43 | 05/24/2014 |是的,是的


现在,您将看到用户20向我写了2条消息(43),因此,在我的消息索引页面上,我想打印线程的最新消息,并以公正的方式对其进行排序

例如:

  • 2014年5月24日-(预览文本:)当然可以-作者:埃里克(线程2)
  • 2014年5月24日-(预览文本:)你好曼努埃尔(螺纹3)
  • 2014年5月21日-(预览文本:)我是女性-桑德拉。 等等
目前,我真正的疑问是:

 SELECT * FROM
    (SELECT * FROM boxmsg 
    LEFT JOIN user ON sender = id WHERE receiver = '959749'
    ORDER BY idmsg DESC) 
 AS temp_tbl
 GROUP BY thread ORDER BY idmsg DESC LIMIT 0,20
因此,它工作正常,但性能是一场真正的灾难。 实际上,它扫描整个数据库,因为派生表中的索引有几个问题

我如何才能得到同样的结果,有一个线程的最新消息

非常感谢你,也为我糟糕的英语感到抱歉。

类似于:

SELECT b.*
FROM boxmsg b
JOIN (
    SELECT thread, MAX(idmsg) as idmsg
    FROM boxmsg x
    GROUP BY thread
) a
    ON a.thread = b.thread
   AND a.idmsg  = b.idmsg
作为线程上的索引,idmsg可能有助于提高性能

这是您的查询:

SELECT *
FROM (SELECT *
      FROM boxmsg LEFT JOIN
           user
           ON sender = id
      WHERE receiver = '959749'
      ORDER BY idmsg DESC
     ) temp_tbl
GROUP BY thread
ORDER BY idmsg DESC
LIMIT 0, 20;
MySQL特别警告不要将
*
分组方式一起使用(请参阅)

有关要执行的操作,请尝试以下查询:

SELECT *
FROM boxmsg bm LEFT JOIN
     user
     ON sender = id
WHERE receiver = '959749' AND
      NOT EXISTS (SELECT 1
                  FROM boxmsg bm2
                  WHERE bm2.receiver = bm.receiver and
                        bm2.thread = bm.thread and
                        bm2.idmsg > bm.idmsg
                 )
ORDER BY idmsg DESC
LIMIT 0, 20;

在运行查询之前,在
boxmsg(receiver,thread,idmsg)
上创建索引,在
user(id)
上创建索引(如果还不存在)。

在boxmsg.receiver和user.sender上有索引吗?