【问题标题】:SQL query on large tables first then slow [closed]先对大表进行 SQL 查询,然后再慢 [关闭]
【发布时间】:2019-12-10 07:44:04
【问题描述】:

查询返回很慢。你知道应该做些什么来提高性能吗?谢谢

$where[] = "FIND_IN_SET(:pid, users.parents)";

$args['books'] = $this->query("SELECT books.*, users.user,
(SELECT COUNT(id) FROM {$this->prefix}books_best WHERE book_id = books.id) AS book_count,
(SELECT COUNT(id) FROM {$this->prefix}books_best WHERE book_id = books.id AND status > 1) AS result_count
FROM {$this->prefix}books AS books
INNER JOIN {$this->prefix}users AS users ON users.id = books.user_id
".(isset($_REQUEST['team']) && !empty($_REQUEST['team']) ? "
    INNER JOIN {$this->prefix}books_best AS tcb ON tcb.book_id = books.id
    INNER JOIN {$this->prefix}book_played AS tm ON tm.id = tcb.book_id AND (tm.home LIKE :team OR tm.away LIKE :team)
" : "")."
".(isset($_REQUEST['book_id']) && !empty($_REQUEST['book_id']) ? "
    INNER JOIN {$this->prefix}books_best AS mcb ON mcb.book_id = books.id AND mcb.book_id = ".intval($_REQUEST['book_id'])."
" : "")."
".(count($array) > 0 ? "WHERE ".implode(" AND ", $where) : "")."
ORDER BY {$orders[$orderable['type']]} {$orderable['order']}
", $array, array('counter' => 'books.id', 'limit' => $_REQUEST['limit'] ?? 25));
$args['pagination'] = $this->pagination();

【问题讨论】:

标签: php mysql sql mariadb


【解决方案1】:

您可以使用联接作为子查询,而不是对每行进行两次选择,以计算此子查询仅执行一次(而不是每行)

  select book_id
    , COUNT(id) book_count
    , sum( case when id is not null and status > 1 then 1 else 0 end) result_count
  FROM {$this->prefix}books_best
  group by book_id

对于表 {$this->prefix}books_best 确保你有一个

   composite index on columns (book_id, status)

基于此假设,您可以将查询重构为

   SELECT books.*, users.user,
    t.book_count,
   t.result_count
  FROM {$this->prefix}books AS books
  INNER JOIN  (
      select book_id
        , COUNT(id) book_count
        , sum( case when id is not null and status > 1  then 1 else 0 end) result_count
      FROM {$this->prefix}books_best
      group by book_id
  ) t on t.book_id = books.id
  INNER JOIN {$this->prefix}users AS users ON users.id = books.user_id
  .....

【讨论】:

  • 非常非常感谢您的关注...我收到错误。SQL 语法;检查与您的 MySQL 服务器版本相对应的手册,以在 ') INNER JOIN 附近使用正确的语法(选择 book_id , COUNT(id) book_count , sum(当 id 不为空且状态 > 1 时的情况)然后 1 else 0 结束) result_count FROM {$this->prefix}books_best group by book_id )
  • @beytullahkantar 回答已更新 .. wearg ) 位置
猜你喜欢
  • 1970-01-01
  • 2018-06-12
  • 2019-12-09
  • 2013-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-29
相关资源
最近更新 更多