1

I have table pages, search_requests and pages_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)
);

I need the similar result as in this question: get latest pages with position from 1 to 100 which belong to a certain search request. I write such sql, it works, but I don't think it is the best way to achieve my goal. It perfoms duplicate queries (join pages with pages_search_requests to select only pages which belong to certain search request) and etc. Is there a way to avoid this?

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

Community
  • 1
  • 1
melihovv
  • 1,055
  • 1
  • 10
  • 15
  • If you like, consider following this simple two-step course of action:1. If you have not already done so, provide proper CREATE and INSERT statements (and/or an sqlfiddle) so that we can more easily replicate the problem. 2. If you have not already done so, provide a desired result set that corresponds with the information provided in step 1. – Strawberry Jul 10 '16 at 14:52
  • Add link to SQL Fiddle – melihovv Jul 10 '16 at 15:24

0 Answers0