MYSQL WHERE-IN Subquery Runs Forever

你。 提交于 2019-12-22 04:42:06

问题


I have a MySQL table. Let's call it Widgets. The Widget table has 3 fields: id, type_id, and name. I want, in one query, to get all the widgets that share a type_id with the Widget named 'doodad'. I've written 2 queries:

  1. Give me the type_id of the widget with the name 'doodad'.
  2. Give me all widgets with that type_id.

This works. Each query, independently achieves its goal.

But when I combine them into a single nested query, it runs forever, infinite loop style. It looks like this:

SELECT * FROM widgets WHERE type_id IN  (
    SELECT type_id FROM widgets WHERE name = 'doodad'
);

Can anyone explain this? Is it because I am writing a nested query which is operating on the same table twice?

Little wheel, why spinnest thou?


回答1:


There is an issue in MySQL and in where even uncorrelated subqueries are treated as though they were correlated and re-evaluated for each row.

In the explain plan the select type will likely be showing as dependant subquery rather than just subquery as would be desired.

I suggest trying the approach described at the end of this article of using a derived table to materialize the inner result set.

Or alternatively you could look at the constify procedure here to see if it will assist you in getting around this issue.




回答2:


Using a JOIN risks duplicating results - an EXISTS will work similar to an IN, without the duplication risk:

SELECT x.* 
  FROM widgets x
 WHERE EXISTS (SELECT NULL
                 FROM WIDGETS y
                WHERE y.name = 'doodah'
                  AND y.type_id = x.type_id)


来源:https://stackoverflow.com/questions/3597021/mysql-where-in-subquery-runs-forever

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