开发者

MySQL JOIN Not Using Primary Key When Joining on Result Returned From Function

开发者 https://www.devze.com 2023-04-08 16:46 出处:网络
Description I\'m trying to JOIN a table using the result of a stored function. The stored function returns an unsigned integer, which is the same type as the field I\'m joining against.

Description

I'm trying to JOIN a table using the result of a stored function. The stored function returns an unsigned integer, which is the same type as the field I'm joining against.

Problem

The field I'm trying to JOIN to is a primary key. My issue is that M开发者_运维技巧ySQL doesn't seem to be using the primary key here.

The relevant lines of the query (shown below) are:

   LEFT JOIN second_db.s
     ON s.id = first_db.find_spend_id(qi.other_type, qi.other_id)

If I replace my function call first_db.find_spend_id(...) with an integer, for example 30, EXPLAIN shows that the primary key is used, and the query is fast. If I use my function, EXPLAIN shows that the primary key is not used, and the query is slow.

Question

Is there some way I can use my function and have MySQL use the primary key when using the result of this function in this join? How should I modify my code in order to attain this most glorious resolution?

Information

Query

EXPLAIN SELECT *
FROM   first_db.qhr
   JOIN first_db.qi
     ON qi.id = qhr.issue_id
        AND qhr.status = 'Accepted'
   LEFT JOIN second_db.s
     ON s.id = first_db.find_spend_id(qi.other_type, qi.other_id)
   JOIN second_db.spend_reports AS sr
     ON sr.id = s.spend_report_id
   JOIN first_db.companies AS b
     ON b.id = s.member_id
   JOIN first_db.brands
     ON brands.id = sr.brand_id
LIMIT  0, 10  

Function

CREATE DEFINER=`user`@`%` FUNCTION `find_spend_id`(lookup_other_type ENUM('One', 'Two'), lookup_other_id INT(10)) 
    RETURNS int(10)
    READS SQL DATA
    BEGIN
        (...snip actual code...)
        return 30;
    END

Explain

id   select_type    table    type    possible_keys    key    key_len    ref    rows    Extra
(...snip...)
1    SIMPLE         s        ALL      NULL            NULL   NULL       NULL   5999    "Using join buffer"
(...snip...)


In my case, what I wanted to achieve was not possible with this approach.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号