MySQL按顺序分组,由多对多关系组成

时间:2016-07-10 14:14:31

标签: mysql group-by sql-order-by

我有表pagessearch_requestspages_search_requests

CREATE TABLE pages
(
  id INT(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
  url VARCHAR(2083) NOT NULL,
  position INT(11) NOT NULL,
  created_at TIMESTAMP,
  updated_at TIMESTAMP
);
CREATE TABLE search_requests
(
    id INT(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
    request VARCHAR(255) NOT NULL,
    created_at TIMESTAMP,
    updated_at TIMESTAMP
);
CREATE TABLE pages_search_requests
(
    page_id INT(10) UNSIGNED NOT NULL,
    search_request_id INT(10) UNSIGNED NOT NULL,
    CONSTRAINT `PRIMARY` PRIMARY KEY (page_id, search_request_id),
    CONSTRAINT pages_search_requests_page_id_foreign FOREIGN KEY (page_id) REFERENCES pages (id),
    CONSTRAINT pages_search_requests_search_request_id_foreign FOREIGN KEY (search_request_id) REFERENCES search_requests (id)
);

我需要与此question中类似的结果:获取位于1到100之间的最新页面,这些页面属于某个搜索请求。我写这样的sql,它有效,但我不认为这是实现我的目标的最佳方式。它执行重复查询(使用pages加入pages_search_requests以仅选择属于特定搜索请求的页面等等。有没有办法避免这种情况?

SELECT *
FROM pages
  INNER JOIN pages_search_requests
    ON pages.id = pages_search_requests.page_id # №3 select all pages which belong to certain search request
  INNER JOIN (SELECT position, max(updated_at) MaxUpdatedAt
              FROM (SELECT position, updated_at
                    FROM pages
                      INNER JOIN pages_search_requests
                        ON pages_search_requests.page_id = pages.id
                    WHERE pages.position <> -1 AND 
                          pages_search_requests.search_request_id = 23)
                    AS SearchRequestPages # №1 select all pages which belong to certain search request
              GROUP BY position)
              AS LatestPages # №2 get MaxUpdatedAt and position
  on LatestPages.MaxUpdatedAt=pages.updated_at and LatestPages.position=pages.position # №4 get latest pages with position from 1 to 100
WHERE pages.position <> -1 AND pages_search_requests.search_request_id = 23
LIMIT 100

SQL Fiddle

0 个答案:

没有答案