简体   繁体   中英

how to avoid full table scan when joining on one foreign key

how to avoid full table scan when joining on one foreign in key below is my sql query when i use explain select it show the query is scanning all the table even with a where clause

SELECT  message_recipients.id, message_recipients.user_type,
COALESCE(guardians.firstname, students.firstname)
    FROM  message_recipients
    LEFT JOIN  students  ON message_recipients.user_id = students.student_id
    LEFT JOIN  guardians  ON message_recipients.user_id = guardians.guardian_id
    WHERE  message_recipients.message_id = 2 

Also i added index on the message_id column still the same here below is the image of the explain select may be am reading it wrong

在此处输入图像描述

the total rows in the table is 8 but the message_id = 2 is just 6 rows and if you check the image you can see its scanning all the 8 rows which is not suppose to be the big question is how do i optimize this to avoid full table scan thanks

One way to avoid a full scan is to use clustered queries with a "with" clause like this:

WITH TB_A AS (
    SELEC
        A.*
    FROM 
        some_table A
    WHERE 
        A.field_1 = 'some condition to filter first table'
)
, TB_B AS (
    SELECT 
        B.*
    FROM 
        other_table B
    WHERE 
        B.field_2 = 'some condition to filter second table if you need that too'
)
SELECT 
    A.*
    , B.*
FROM 
    TB_A A 
INNER JOIN 
    TB_B B
    ON A.field_1 = B.field_1 --Running without full scan on join and much faster
;

;D

A FOREIGN KEY creates an INDEX , but that INDEX may not be optimal. See if these 'composit' indexes are better:

message_recipients:  INDEX(message_id, user_id,  id, user_type)
guardians:  INDEX(guardian_id,  firstname)
students:   INDEX(student_id,   firstname)

When adding a composite index, DROP index(es) with the same leading columns. That is, when you have both INDEX(a) and INDEX(a,b), toss the former.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM