Here is a method using Dynamic SQL
SET group_concat_max_len = 1048576;
SELECT GROUP_CONCAT(CONCAT('SELECT * FROM table WHERE column LIKE ''',prfx,'%''')
SEPARATOR ' UNION ')
INTO @sql FROM (SELECT 'AAA' prfx UNION SELECT 'BBB' UNION SELECT 'CCC') pfxkeys;
PREPARE s FROM @sql; EXECUTE s; DEALLOCATE PREPARE s;
So that you understand what this is doing, please note what @sql
becomes:
mysql> SELECT @sql\G
*************************** 1. row ***************************
@sql: SELECT * FROM table WHERE column LIKE 'AAA%' UNION SELECT * FROM table WHERE column LIKE 'BBB%' UNION SELECT * FROM table WHERE column LIKE 'CCC%'
Let me format the output a little more
SELECT * FROM table WHERE column LIKE 'AAA%' UNION
SELECT * FROM table WHERE column LIKE 'BBB%' UNION
SELECT * FROM table WHERE column LIKE 'CCC%'
The only thing you need to focus on in scripting the pfxkeys
subquery.
In your example, you need
(
SELECT 'AAA' prfx UNION
SELECT 'BBB' UNION
SELECT 'CCC'
) pfxkeys
If you have more prefix keys like DDD
and EEE
, you just add to this subquery:
(
SELECT 'AAA' prfx UNION
SELECT 'BBB' UNION
SELECT 'CCC' UNION
SELECT 'DDD' UNION
SELECT 'EEE'
) pfxkeys