Match the elements of an array in a MySQL query

MySQLMySQLi Database

Let us first create a table table −

mysql> create table DemoTable1523
   -> (
   -> Id int,
   -> Value int
   -> );
Query OK, 0 rows affected (0.76 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable1523 values(1,56);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1523 values(2,78);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable1523 values(1,34);
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable1523 values(2,45);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable1523 values(1,99);
Query OK, 1 row affected (0.10 sec)

Display all records from the table using select statement −

mysql> select * from DemoTable1523;

This will produce the following output −

+------+-------+
| Id   | Value |
+------+-------+
|    1 |    56 |
|    2 |    78 |
|    1 |    34 |
|    2 |    45 |
|    1 |    99 |
+------+-------+
5 rows in set (0.00 sec)

Following is the query to match the elements of array. Here, we are selecting id with matching values 34, 99, and 56 −

mysql> select Id from DemoTable1523
   -> where Value IN ('34','99','56')
   -> group by Id
   -> having count(*)=3;

This will produce the following output −

+------+
| Id   |
+------+
|    1 |
+------+
1 row in set (0.00 sec)
raja
Published on 11-Dec-2019 11:01:48
Advertisements