MySQL में REGEXP से पैटर्न मिलान के साथ चयन करें
इसके लिए आप नियमित अभिव्यक्ति का उपयोग कर सकते हैं। आइए पहले एक टेबल बनाते हैं:
mysql> create table DemoTable
(
ProductId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
ProductName varchar(20)
); Query OK, 0 rows affected (0.19 sec)
इन्सर्ट कमांड से टेबल में कुछ रिकॉर्ड डालें:
mysql> insert into DemoTable(ProductName) values('Product-1'); Query OK, 1 row affected (0.05 sec)
mysql> insert into DemoTable(ProductName) values('Product2'); Query OK, 1 row affected (0.06 sec)
mysql> insert into DemoTable(ProductName) values('Product1'); Query OK, 1 row affected (0.04 sec)
mysql> insert into DemoTable(ProductName) values('Product-3'); Query OK, 1 row affected (0.05 sec)
mysql> insert into DemoTable(ProductName) values('Product3'); Query OK, 1 row affected (0.05 sec)
mysql> insert into DemoTable(ProductName) values('Product-4'); Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable(ProductName) values('Product4'); Query OK, 1 row affected (0.05 sec)
सेलेक्ट स्टेटमेंट से टेबल के सभी रिकॉर्ड प्रदर्शित करें:
mysql> select *from DemoTable;
आउटपुट:
+-----------+-------------+ | ProductId | ProductName | +-----------+-------------+ | 1 | Product-1 | | 2 | Product2 | | 3 | Product1 | | 4 | Product-3 | | 5 | Product3 | | 6 | Product-4 | | 7 | Product4 | +-----------+-------------+ 7 rows in set (0.00 sec)
एकाधिक मिलान वाले स्ट्रिंग वाले ग्रुप्ड रिकॉर्ड के लिए क्वेरी:
mysql> select *from DemoTable where ProductName regexp 'Product[1234].*';
आउटपुट:
+-----------+-------------+ | ProductId | ProductName | +-----------+-------------+ | 2 | Product2 | | 3 | Product1 | | 5 | Product3 | | 7 | Product4 | +-----------+-------------+ 4 rows in set (0.00 sec)
व्याख्या: रेगेक्स Product[1234].* "Product" से शुरू होने वाले, उसके बाद 1,2,3, या 4, फिर किसी भी वर्ण से मेल खाता है। यह 'Product-1' (हाइफ़न के कारण), 'Product2', 'Product1', 'Product-3', 'Product3', 'Product-4', 'Product4' से मेल खाता है। लेकिन आउटपुट केवल बिना हाइफ़न वाले दिखाता है क्योंकि .* हाइफ़न से मेल नहीं खाता? वास्तव में पैटर्न Product[1234] के बाद .* है, इसलिए 'Product-1' में 'Product' के बाद '-' है, जो [1234] से मेल नहीं खाता। सही पैटर्न Product[-]?[1234] होगा।