How to use a SQL Function with INNER JOIN in MySQL?

落爺英雄遲暮 提交于 2019-12-23 01:42:00

问题


I have a function "fnc_FindIssueId" which accepts an object id and return its assigned issue Id.

When I call the function using pure select statements, it works fine:

select fnc_FindIssueId(150083); // returns 1 as issueId for objectId of 150083
select fnc_FindIssueId(150072); // returns 2 as issueId for objectId of 150072

But when I use it within an Inner Join, it goes into a never-ending loop:

select so.id, si.id
from smart_objects as so 
       LEFT OUTER join smart_issues as si 
        on si.id = fnc_FindIssueId(so.id)
where so.id in (150083, 150072);

What's the reason and how to resolve it?


回答1:


It does not perform never-ending loop.

The reason for that is because the server performs FULL TABLE SCAN which is very slow. This condition si.id = fnc_FindIssueId(so.id) doesn't use an index even if you have define one on si.id and so.id.

The best ways you can do are:

  • to alter the table smart_objects
  • another column for the assigned issue Id
  • define an index on the new column



回答2:


The workaround was to create a new view with ObjectId and IssueId columns then calling that function from within that view! but it has become very slow now.

CREATE ALGORITHM=UNDEFINED DEFINER=`mysql`@`%` SQL SECURITY DEFINER VIEW `vw_smart_objectissue` AS select `so`.`id` AS `objectid`,`fnc_FindIssueId`(`so`.`id`) AS `issueid` from `smart_objects` `so` order by `so`.`id`$$


来源:https://stackoverflow.com/questions/14811363/how-to-use-a-sql-function-with-inner-join-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!