如何通过内部联接到另一个表来优化自联接选择

时间:2020-03-06 18:07:46

标签: mysql inner-join query-performance self-join

我有一个留言板,其中所有消息,线程和留言板都存储在一个“页面”表中。我想列出所有消息,包括他们的先后顺序。自联接的速度很快,但是当我使用内部联接到另一个表来包括消息作者时,查询速度将减慢到几秒钟。有什么方法可以更好地构造查询吗?

数据库如下:

pagetypes
type        | typename
———————————————————
15           board
16           thread
17           message 


pages
pageid  |  type | parentid    | authorid | title                
————————————————————————————————————————————
1          15      null          1        "BigBoard"
2          16      1             1        "Introductions"
3          17      2             2        “Hello everyone!”
4          17      2             1        “Welcome!”
5          16      1             1         “News and Gossip”
6          17      5             3        “Whats new?”

users
id    | name
————————————————————
1       "Peter"
2       "Paul"
3       "Mary"

我的选择查询是:

select p.title as message_title, u.name, t.title as thread_title, b.title as board_title
from pages as p
join pages as t on p.parentid=t.pageid
join pages as b on t.parentid=b.pageid 
join users as u on p.authorid=u.id
where p.type=17

结果如下:

message_title       |   name    |   thread_title       |    board_title
-----------------------------------------------------------------------
“Hello everyone!”       Paul        "Introductions"         "BigBoard"
“Welcome                Peter       "Introductions"         "BigBoard"
“What’s new?””          Mary        "News and Gossip"       "BigBoard"

如果我将用户带到那里,则查询(400K页面上)为30毫秒。将用户添加到请求后,查询最多需要3秒钟。

这是表格说明:

CREATE TABLE `pages` (
  `pageid` int(10) unsigned NOT NULL DEFAULT '0',
  `parentid` int(10) unsigned NOT NULL DEFAULT '0',
  `authorid` int(10) unsigned NOT NULL DEFAULT '0',
  `type` smallint(5) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`pageid`),
  KEY `text_key` (`parentid`,`type`),
  KEY `type_key` (`type`),
  KEY `byAuthor` (`authorid`,`type`)
) 

CREATE TABLE `users` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL DEFAULT '',
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
)

1 个答案:

答案 0 :(得分:0)

我想我解决了。我向用户添加了LEFT JOIN,使查询时间缩短到30毫秒。

="direct text input"&A3&" more text"&CHAR(34)&"Newline with new text"