I have fields that look like this:
meta_key | meta_value |
---|---|
schedule_1_date | 2021/2/7 |
schedule_1_lesson | 100 |
schedule_2_date | 2020/12/30 |
schedule_2_lesson | 105 |
schedule_3_date | 2021/2/8 |
schedule_3_lesson | 90 |
schedule_4_date | 2021/5/10 |
schedule_4_lesson | 91 |
I want to select the data to meet the condition:
For example, with the condition above, I will get these data:
meta_key | meta_value |
---|---|
schedule_1_date | 2021/2/7 |
schedule_1_lesson | 100 |
schedule_3_date | 2021/2/8 |
schedule_3_lesson | 90 |
The code I've tried so far
SELECT * FROM 'table_name' WHERE (meta_key LIKE 'schedule_%_date' AND meta_value IN ('2021/02/07','2021/02/08')) OR (meta_key LIKE 'schedule_%_lesson')
Check this one out:
SELECT tt.meta_key AS lesson_key, tt.meta_value AS lesson_value,
d.meta_key AS date_key, d.meta_value AS date_value
FROM `table_name` tt
JOIN
(SELECT t.*, REPLACE(REPLACE(t.meta_key, 'schedule_', ''), '_date', '') AS key_num
FROM `table_name` t
WHERE t.meta_key LIKE '%schedule%date%'
AND t.meta_value IN ('2021/2/7', '2021/2/8')) d
ON d.key_num = REPLACE(REPLACE(tt.meta_key, 'schedule_', ''), '_lesson', '')
WHERE tt.meta_key LIKE '%schedule%lesson%'
It outputs data in a slightly different format, thought it might work for you as well:
lesson_key | lesson_value | date_key | date_value |
---|---|---|---|
schedule_1_lesson | 100 | schedule_1_date | 2021/2/7 |
schedule_3_lesson | 90 | schedule_3_date | 2021/2/8 |
This query though might not be optimal from indexes utilization perspective. Make sure to take this into consideration. Using %
wildcard in the LIKE
statements in the middle of search string reduces the performance of index.