Home Database Mysql Tutorial mysql中的IN和FIND_IN_SET的查询问题_MySQL

mysql中的IN和FIND_IN_SET的查询问题_MySQL

Jun 01, 2016 pm 01:29 PM
mysql

bitsCN.com

mysql中的IN和FIND_IN_SET的查询问题

 

原来以为mysql可以进行这样的查询

select id, list, name from table where 'daodao' IN (list);   
Copy after login
(一)

注:1. table含有三个字段id:int, list:varchar(255), name:varchar(255)

实际上这样是不行的,这样只有当'daodao'是list中的第一个元素(我测试的时候貌似是第一个也是不行的,只有当list字段的值等于daodao时才是对的)时,查询才有效,否则都的不到结果,即使'daodao'真的再list中

测试代码:

CREATE TABLE `test` (  `id` int(8) NOT NULL auto_increment,  `name` varchar(255) NOT NULL,  `list` varchar(255) NOT NULL,  PRIMARY KEY  (`id`))INSERT INTO `test` VALUES (1, 'name', 'daodao,xiaohu,xiaoqin');INSERT INTO `test` VALUES (2, 'name2', 'xiaohu,daodao,xiaoqin');INSERT INTO `test` VALUES (3, 'name3', 'xiaoqin,daodao,xiaohu');test1:sql = select * from `test` where 'daodao' IN (`list`);
Copy after login

得到结果空值.

test2:sql = select * from `test` where FIND_IN_SET('daodao',`list`);
Copy after login

得到三条数据。

        1 name daodao,xiaohu,xiaoqin        2 name2 xiaohu,daodao,xiaoqin        3 name3 xiaoqin,daodao,xiaohu
Copy after login

修改表数据

update `test` set `list`='daodao' where `id`='1';
Copy after login

然后执行test1的sql,可以返回一条结果。

再来看看这个:

select id, list, name from table where 'daodao' IN ('libk', 'zyfon', 'daodao');  
Copy after login
(二)

这样是可以的

---------------------------------------------------------

这两条到底有什么区别呢?为什么第一条不能取得正确的结果,而第二条却能取得结果。

原因其实是(一)中 (list) list是变量, 而(二)中 ('libk', 'zyfon', 'daodao')是常量

所以如果要让(一)能正确工作,需要用find_in_set():

select id, list, name from table where FIND_IN_SET( 'daodao' , list);
Copy after login
(一)的改进版。

总结:所以如果list是常量,则可以直接用IN, 否则要用FIND_IN_SET()函数

FIND_IN_SET(str,strlist)

假如字符串str 在由N 子链组成的字符串列表strlist 中, 则返回值的范围在 1 到 N 之间 。一个字符串列表就是一个由一些被‘,’符号分开的自链组成的字符串。如果第一个参数是一个常数字符串,而第二个是type SET列,则 FIND_IN_SET() 函数被优化,使用比特计算。如果str不在strlist 或strlist 为空字符串,则返回值为 0 。如任意一个参数为NULL,则返回值为NULL。 这个函数在第一个参数包含一个逗号(‘,’)时将无法正常运行。

mysql> SELECT FIND_IN_SET('b','a,b,c,d');        -> 2
Copy after login

延伸用法,利用FIND_IN_set排序

eg:$ids = '9,3,45,1,8,2,6';$sql = "... WHERE goods_id IN('{$ids}') ORDER BY FIND_IN_SET(goods_id, '{$ids}')";
Copy after login

 


bitsCN.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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mysql whether to change table lock table mysql whether to change table lock table Apr 08, 2025 pm 05:06 PM

When MySQL modifys table structure, metadata locks are usually used, which may cause the table to be locked. To reduce the impact of locks, the following measures can be taken: 1. Keep tables available with online DDL; 2. Perform complex modifications in batches; 3. Operate during small or off-peak periods; 4. Use PT-OSC tools to achieve finer control.

RDS MySQL integration with Redshift zero ETL RDS MySQL integration with Redshift zero ETL Apr 08, 2025 pm 07:06 PM

Data Integration Simplification: AmazonRDSMySQL and Redshift's zero ETL integration Efficient data integration is at the heart of a data-driven organization. Traditional ETL (extract, convert, load) processes are complex and time-consuming, especially when integrating databases (such as AmazonRDSMySQL) with data warehouses (such as Redshift). However, AWS provides zero ETL integration solutions that have completely changed this situation, providing a simplified, near-real-time solution for data migration from RDSMySQL to Redshift. This article will dive into RDSMySQL zero ETL integration with Redshift, explaining how it works and the advantages it brings to data engineers and developers.

Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Apr 08, 2025 pm 07:12 PM

1. Use the correct index to speed up data retrieval by reducing the amount of data scanned select*frommployeeswherelast_name='smith'; if you look up a column of a table multiple times, create an index for that column. If you or your app needs data from multiple columns according to the criteria, create a composite index 2. Avoid select * only those required columns, if you select all unwanted columns, this will only consume more server memory and cause the server to slow down at high load or frequency times For example, your table contains columns such as created_at and updated_at and timestamps, and then avoid selecting * because they do not require inefficient query se

The primary key of mysql can be null The primary key of mysql can be null Apr 08, 2025 pm 03:03 PM

The MySQL primary key cannot be empty because the primary key is a key attribute that uniquely identifies each row in the database. If the primary key can be empty, the record cannot be uniquely identifies, which will lead to data confusion. When using self-incremental integer columns or UUIDs as primary keys, you should consider factors such as efficiency and space occupancy and choose an appropriate solution.

Can mysql handle multiple connections Can mysql handle multiple connections Apr 08, 2025 pm 03:51 PM

MySQL can handle multiple concurrent connections and use multi-threading/multi-processing to assign independent execution environments to each client request to ensure that they are not disturbed. However, the number of concurrent connections is affected by system resources, MySQL configuration, query performance, storage engine and network environment. Optimization requires consideration of many factors such as code level (writing efficient SQL), configuration level (adjusting max_connections), hardware level (improving server configuration).

Can mysql run on android Can mysql run on android Apr 08, 2025 pm 05:03 PM

MySQL cannot run directly on Android, but it can be implemented indirectly by using the following methods: using the lightweight database SQLite, which is built on the Android system, does not require a separate server, and has a small resource usage, which is very suitable for mobile device applications. Remotely connect to the MySQL server and connect to the MySQL database on the remote server through the network for data reading and writing, but there are disadvantages such as strong network dependencies, security issues and server costs.

Can mysql return json Can mysql return json Apr 08, 2025 pm 03:09 PM

MySQL can return JSON data. The JSON_EXTRACT function extracts field values. For complex queries, you can consider using the WHERE clause to filter JSON data, but pay attention to its performance impact. MySQL's support for JSON is constantly increasing, and it is recommended to pay attention to the latest version and features.

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

See all articles