Home > Database > Mysql Tutorial > body text

Can MySQL's FIND_IN_SET or an Equivalent Function Utilize Indices?

Patricia Arquette
Release: 2024-11-05 21:22:02
Original
133 people have browsed it

Can MySQL's FIND_IN_SET or an Equivalent Function Utilize Indices?

Can MySQL FIND_IN_SET or an Equivalent Utilize Indices?

The query SELECT * FROM Foo WHERE FIND_IN_SET(id, '2,3') does not take advantage of the primary key index. This is evident when comparing its EXPLAIN output to the output for SELECT * FROM Foo WHERE id IN (2,3) which does utilize the index.

Objective: Construct a stored procedure that behaves like the second query, utilizing the index without prior knowledge of the comma-separated string containing the IDs.

Solution:

Create a prepared statement that accepts a string as a parameter:

CREATE PROCEDURE my_sp(@id_string NCHAR(1000))
Copy after login

The prepared statement can then be executed with the comma-separated string as an argument:

EXEC my_sp '2,3'
Copy after login

This approach achieves the following desired conditions:

  • type is range (not ALL)
  • key is not NULL

These conditions indicate that the index is being used.

Security Considerations:

Prepared statements mitigate the risk of SQL injection attacks. However, it's still crucial to ensure that user-supplied data is sanitized to prevent 2nd level SQL injection attacks.

The above is the detailed content of Can MySQL's FIND_IN_SET or an Equivalent Function Utilize Indices?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!