1

我对 SQL 查询有疑问,有什么方法可以加快这个查询的速度吗?表字包含 14 000 行,查询在 localhost 上花费了 4.5631 秒。

    SELECT 
    (SELECT SUM((SELECT COUNT(*)
                    FROM word w
                    WHERE w.lecture_id = l._id AND active = 1))
        FROM lecture l
        WHERE l.book_id = b._id) AS active_word_count,
    (SELECT SUM((SELECT COUNT(*)
                 FROM word w
                 WHERE w.lecture_id = l._id))
        FROM lecture l
        WHERE book_id = b._id) AS word_count,
    (SELECT COUNT(*)
     FROM lecture l
     WHERE l.book_id = b._id) AS lecture_count,
    b._id,
    b.name,
    b.version
FROM book b



CREATE TABLE book (
  _id int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  version tinyint(3) unsigned NOT NULL,
  lang tinyint(4) NOT NULL DEFAULT '1',
  PRIMARY KEY (_id)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=21 ;

CREATE TABLE lecture (
  _id int(11) NOT NULL AUTO_INCREMENT,
  book_id int(11) NOT NULL,
  lecture_name varchar(255) NOT NULL,
  PRIMARY KEY (_id)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=155 ;

CREATE TABLE word (
  _id int(11) NOT NULL AUTO_INCREMENT,
  question varchar(255) NOT NULL,
  answer varchar(255) NOT NULL,
  active tinyint(1) NOT NULL,
  lecture_id int(11) NOT NULL,
  PRIMARY KEY (_id)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

查询返回数据,女巫可在此处获得:http: //pastebin.com/80KNsU7Y

谢谢你的帮助。

4

2 回答 2

4

我添加了几个索引,可以加快以这种方式编写的查询。他们也可能对原件有所帮助。http://sqlfiddle.com/#!2/bdcf8/1

Select
  Sum(Case When w.Active = 1 Then 1 Else 0 End) As active_word_count,
  Count(w._id) As word_count,
  Count(Distinct l._id) As lecture_count,
  b._id,
  b.name,
  b.version
From
  Book b
    Left Outer Join
  Lecture l
    On l.book_id = b._id
    Left Outer Join
  Word w
    On w.lecture_id = l._id
Group By
   b._id,
   b.name,
   b.version
于 2012-11-12T12:46:22.683 回答
2

我添加了一些 JOIN。所以现在应该更快了。http://sqlfiddle.com/#!2/eec80/15

SELECT
    (SELECT COUNT(*)
        FROM word w
        JOIN lecture l ON l._id = w.lecture_id
        WHERE l.book_id = b._id
        AND w.active = 1) AS active_word_count,
    (SELECT COUNT(*)
        FROM word w
        JOIN lecture l ON  w.lecture_id = l._id
        WHERE l.book_id = b._id) AS word_count,
    (SELECT COUNT(*)
        FROM lecture l
        WHERE l.book_id = b._id) AS lecture_count,
    b._id,
    b.name,
    b.version
FROM book b
于 2012-11-12T13:03:34.237 回答