简体   繁体   中英

Using a join in Mysql update statement instead of sub-query

I'm currently using the following to update a table of mine:

UPDATE Check_Dictionary 
               SET InDict = "No" WHERE (Leagues, Matches, Line) IN (SELECT * FROM (
               SELECT Leagues, Matches, Line FROM Check_Dictionary 
               WHERE InDict = "No")as X)

However, when I have large data sets (40k+ rows) this seems to be fairly inefficient/slow. All of the searching I'm doing suggests that joins are far more efficient for this sort of thing than a sub-query. However, being a mysql newbie I'm not sure of the best way to do it.

My table may have multiple rows where the League/Matches/Line fields are the same. Generally the InDict field on these rows will be "Yes". However, if one of them is "No" I need to update all of the other rows with the same League/Matches/Line columns to "No" as well (so they all have a value of "No").

Would using a join in Mysql update statement instead of sub-query be more efficient?

How can I do it using a join?

I would think a join should be faster, but it depends on indexing and other things, you should try it for yourself to see which performs better (and maybe use explain to analyze the queries).

As for syntax, any of these should work:

UPDATE Check_Dictionary c1
JOIN (
  SELECT Leagues, Matches, Line 
  FROM Check_Dictionary 
  WHERE InDict = "No"
) AS X USING (Leagues, Matches, Line)
SET InDict = "No" 

UPDATE Check_Dictionary AS c1
JOIN Check_Dictionary AS c2 USING (Leagues, Matches, Line) 
SET c1.InDict = "No" 
WHERE c2.InDict = "No"

The update join query given by "jpw" was correct you can use it, I don't want to repeat. Having said, i just want to post join is faster than subquery obviously especially if you want to update 40K+ rows. Below is the data from MySQL documentation says about the same.

A LEFT [OUTER] JOIN can be faster than an equivalent subquery because the server might be able to optimize it better—a fact that is not specific to MySQL Server alone. Prior to SQL-92, outer joins did not exist, so subqueries were the only way to do certain things. Today, MySQL Server and many other modern database systems offer a wide range of outer join types. MySQL Server supports multiple-table DELETE statements that can be used to efficiently delete rows based on information from one table or even from many tables at the same time. Multiple-table UPDATE statements are also supported. See Section 13.2.2, “DELETE Syntax”, and Section 13.2.10, “UPDATE Syntax”.

Source : http://dev.mysql.com/doc/refman/5.1/en/rewriting-subqueries.html

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