sql >> Database teknologi >  >> RDS >> Mysql

Nøjagtig sideinddeling med venstre Joins

Her er din oprindelige forespørgsel

SELECT l.location_id, l.location_name, 
       t.type_id, t.type_name, 
       i.location_address, i.location_phone 
FROM location AS l 
LEFT JOIN location_information AS i ON (l.location_id = i.location_id) 
LEFT JOIN location_types AS t ON (l.location_type_id = t.type_id) 
ORDER BY l.location_id DESC 
LIMIT 10 

Du udfører pagineringen sidst. Hvis du omfaktorerer denne forespørgsel, kan du udføre pagineringen tidligere.

SELECT l.location_id, l.location_name, 
       t.type_id, t.type_name, 
       i.location_address, i.location_phone 
FROM
    (SELECT location_id,location_type_id FROM location
    ORDER BY location_id LIMIT 10) AS k
    LEFT JOIN location AS l ON (k.location_id = l.location_id)
    LEFT JOIN location_information AS i ON (k.location_id = i.location_id) 
    LEFT JOIN location_types AS t ON (l.location_type_id = t.type_id) 
;

Bemærk, at jeg oprettede en underforespørgsel kaldet k . De 10 nøgler bliver afhentet og bestilt FØRST !!!

Så kan JOIN'erne fortsætte derfra, håber at bruge kun 10 location_id'er.

Hvad vil hjælpe underforespørgslen k er et indeks, der bærer location_id og location_type_id

ALTER TABLE location ADD INDEX id_type_ndx (location_id,location_type_id);

Her er noget andet, du måske kan lide ved denne tilgang

Hvordan forespørger du efter de næste 10 id'er (id 11 - 20)? Sådan:

SELECT l.location_id, l.location_name, 
       t.type_id, t.type_name, 
       i.location_address, i.location_phone 
FROM
    (SELECT location_id,location_type_id FROM location
    ORDER BY location_id LIMIT 10,10) AS k
    LEFT JOIN location AS l ON (k.location_id = l.location_id)
    LEFT JOIN location_information AS i ON (k.location_id = i.location_id) 
    LEFT JOIN location_types AS t ON (l.location_type_id = t.type_id) 
;

Alt du skal gøre er at ændre LIMIT klausul i underforespørgsel k med hver ny side.

  • LIMIT 20,10
  • LIMIT 30,10
  • og så videre...

Jeg kan forbedre refactoring ved at fjerne placeringstabellen og få underforespørgsel k til at bære de nødvendige felter som dette:

SELECT k.location_id, k.location_name, 
       t.type_id, t.type_name, 
       i.location_address, i.location_phone 
FROM
    (SELECT location_id,location_type_id,location_name
    FROM location ORDER BY location_id LIMIT 10,10) AS k
    LEFT JOIN location_information AS i ON (k.location_id = i.location_id) 
    LEFT JOIN location_types AS t ON (k.location_type_id = t.type_id) 
;

At lave det ekstra indeks ville ikke være nødvendigt for denne version.

Prøv det!!!



  1. Sådan løses ORA-00900

  2. SQL-standard UPSERT-kald

  3. MySQL-databasedesign til en liste over tjenester

  4. Forespørgselshastighed baseret på rækkefølgen af ​​kolonner