Home > Database > Mysql Tutorial > What is the method of using string in in condition in mysql

What is the method of using string in in condition in mysql

王林
Release: 2023-05-31 10:17:03
forward
1826 people have browsed it

The in condition in mysql uses a string

Scenario

When sql uses in as a condition, a parameter is used to satisfy the query condition, and passing in the string directly cannot satisfy the condition.

select id,name from user where id in(?)
Copy after login

Method

Use FIND_IN_SET(str,strlist) function

select id,name from user where FIND_IN_SET(id,#{strlist})
Copy after login
  • ##str: Conditional field

  • strlist: matching value set

  • select id,name from user where FIND_IN_SET(id,'111,22,333')
    Copy after login
mysql query in condition parameter is a string with comma, the query result is wrong

If there is the following sql:

SELECT
    (
        SELECT
            GROUP_CONCAT(content)
        FROM
            account_limit_user ur
        WHERE
            ur.id IN (T1.limit_user)
        GROUP BY
            ur.id
    ) AS limit_user
FROM
    account T1
WHERE
    1 = 1
Copy after login

T1.limit_user is the value queried from the account table

‘9,8,4’

Query sql The correct query result should be:

Not recommended, promote customers, promote customers

The actual result is:

Not recommended

Reason:

If in in mysql is a string, it will be automatically converted into int type. The following method is used internally:

CAST('4,3' AS INT)
Copy after login

Because the comma is mistakenly written as a semicolon, "4,3" becomes "4;", so the result of the above query SQL only contains the first one.

Solution

FIND_IN_SET('查询的值(如:1)', '使用逗号隔开的字符串集合,如:('1,2,3')')
Copy after login

Correct sql

SELECT
    (
        SELECT
            GROUP_CONCAT(content)
        FROM
            account_limit_user ur 
        WHERE
            FIND_IN_SET(ur.id, T1.limit_user) > 0
    ) AS limit_user,
    T1.limit_user limit_userid
FROM
    account T1
WHERE
    1 = 1
Copy after login

The above is the detailed content of What is the method of using string in in condition in mysql. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template