Computer >> 컴퓨터 >  >> 프로그램 작성 >> MySQL

MySQL IN()을 사용하여 쿼리를 선택하고 정렬을 피하십시오.

<시간/>

IN()을 사용하면 특정 필드에 대한 결과를 정렬합니다. 이를 방지하려면 필드에 ORDER BY 및 FIND_IN_SET()을 사용하십시오.

find_in_set()을 이해하기 위해 테이블을 생성해 보겠습니다. 테이블을 생성하는 쿼리는 다음과 같습니다 -

mysql> create table ProductStock
   -> (
   -> ProductId int,
   -> ProductName varchar(20),
   -> ProductQuantity int,
   -> ProductPrice float
   -> );
Query OK, 0 rows affected (0.79 sec)

이제 insert 명령을 사용하여 테이블에 일부 레코드를 삽입할 수 있습니다. 쿼리는 다음과 같습니다 -

mysql> insert into ProductStock values(1,'Product-101',10,500.56);
Query OK, 1 row affected (0.20 sec)
mysql> insert into ProductStock values(25,'Product-111',5,150.00);
Query OK, 1 row affected (0.21 sec)
mysql> insert into ProductStock values(67,'Product-311',7,1000.50);
Query OK, 1 row affected (0.60 sec)
mysql> insert into ProductStock values(55,'Product-561',8,900.00);
Query OK, 1 row affected (0.24 sec)
mysql> insert into ProductStock values(75,'Product-221',15,670.56);
Query OK, 1 row affected (0.14 sec)

select 문을 사용하여 테이블의 모든 레코드를 표시합니다. 쿼리는 다음과 같습니다 -

mysql> select *from ProductStock;

출력

+-----------+-------------+-----------------+--------------+
| ProductId | ProductName | ProductQuantity | ProductPrice |
+-----------+-------------+-----------------+--------------+
|         1 | Product-101 |              10 |       500.56 |
|        25 | Product-111 |               5 |          150 |
|        67 | Product-311 |               7 |       1000.5 |
|        55 | Product-561 |               8 |          900 |
|        75 | Product-221 |              15 |       670.56 |
+-----------+-------------+-----------------+--------------+
5 rows in set (0.00 sec)

다음은 쿼리에 find_in_set()을 사용하는 쿼리입니다 -

mysql> select *from ProductStock
   -> where ProductId IN(25,55,67,75,1)
   -> order by find_in_set(ProductId,'25,55,67,75,1');

출력

+-----------+-------------+-----------------+--------------+
| ProductId | ProductName | ProductQuantity | ProductPrice |
+-----------+-------------+-----------------+--------------+
|        25 | Product-111 |               5 |          150 |
|        55 | Product-561 |               8 |          900 |
|        67 | Product-311 |               7 |       1000.5 |
|        75 | Product-221 |              15 |       670.56 |
|         1 | Product-101 |              10 |       500.56 |
+-----------+-------------+-----------------+--------------+
5 rows in set (0.31 sec)