1. 程式人生 > >sql語句中當條件的數量非常大時where...in條件子句用什麼更好的方法代替?

sql語句中當條件的數量非常大時where...in條件子句用什麼更好的方法代替?

When you need to pass a list of parameters into a MySQL, there are at least two method to do this:

  • Issue a dynamical query which would fill an IN list with constant values
  • Fill a temporary table with these values then use it in a JOIN

The second method is considered better for many reasons (you can easily reuse the values, it's more injection-proof etc.)

Leaving all these issues aside, let's compare these methods performance-wise.

We will create a table of 50,000 records, pass a list of 500 parameters (using both methods) and see which is faster:

We have created two stored procedures.

The first procedure, prc_temporary, fills the temporary value using a dynamic query then issues the query using a JOIN

 in a loop.

The second procedure, prc_range, just uses the IN list in a dynamic query, also in a loop.

Let's run both procedures:

1.CALL prc_list(1000)
_cnt
1001
1 row fetched in 0.0001s (4.1218s)
1.CALL prc_temporary(1000)
_cnt
1001
1 row fetched in 0.0001s (1.9406s)

However, if we change the procedures and leave but 20

 parameters:

, both procedures have almost the same performance:

1.CALL prc_list(1000)
_cnt
1001
1 row fetched in 0.0001s (0.6315s)
1.CALL prc_temporary(1000)
_cnt
1001
1 row fetched in 0.0001s (0.6408s)

We see that for a large list of parameters, passing them in a temporary table is much faster that as a constant list, while for small lists performance is almost the same.

Using a temporary table is the best way to pass large arrays of parameters in MySQL.