- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can I achieve similar result like using a loop in MySQL WHERE clause to display only alternate ID records?
Get similar results using MySQL IN(). Let us first create a table −
mysql> create table DemoTable ( ClientId int, ClientName varchar(100), ClientAge int ); Query OK, 0 rows affected (0.70 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values(100,'Chris',34); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values(101,'Robert',31); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(103,'David',33); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values(104,'Mike',45); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values(105,'Sam',39); Query OK, 1 row affected (0.09 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----------+------------+-----------+ | ClientId | ClientName | ClientAge | +----------+------------+-----------+ | 100 | Chris | 34 | | 101 | Robert | 31 | | 103 | David | 33 | | 104 | Mike | 45 | | 105 | Sam | 39 | +----------+------------+-----------+ 5 rows in set (0.00 sec)
Following is the query to get similar results like a loop using MySQL IN() −
mysql> select ClientId,ClientName,ClientAge from DemoTable where ClientId IN(101,103,105);
This will produce the following output −
+----------+------------+-----------+ | ClientId | ClientName | ClientAge | +----------+------------+-----------+ | 101 | Robert | 31 | | 103 | David | 33 | | 105 | Sam | 39 | +----------+------------+-----------+ 3 rows in set (0.00 sec)
Advertisements