I’m noob in MySQL…
It is difficult to describe my task, so I will show it with an example.
I have two tables:
meta_data
:
id key value
1 property_1 1,2,54,2
1 property_2 23424
1 property_3 cat
1 property_4 4324
1 property_5 3231
1 property_6 45
1 property_7 423424
1 property_8 868
1 property_9 2424
1 property_10 886
1 property_11 535
1 property_12 3434
1 property_13 686
1 property_14 55
1 property_15 23424
1 property_16 54534
1 property_17 868
1 property_18 4556
1 property_19 5345
1 property_20 43535
2 property_1 54,92,22
2 property_2 43443
2 property_3 dog
2 property_4 343
2 property_5 2342
2 property_6 34
users
:
id email
1 [email protected]
2 [email protected]
3 [email protected]
4 [email protected]
5 [email protected]
6 [email protected]
7 [email protected]
8 [email protected]
9 [email protected]
And after call the stored procedure I want to get this:
id property_1 property_2 property_3 email
1 "1,2,54,2" "23424" "cat" "[email protected]"
The procedure must get an input parameter
(for example "cat") and:
- find the line where
property_3
is equal to the inputparameter
and get the id from this row (for example "1"), - select the fields, that I need, from the
meta_data
table, where theid
is equal to ourid
from the first point (for exampleproperty_1
,property_2
,property_3
), - then rotate them from rows to columns,
- and finally add
email
fromuser
table with the sameid
.
All this if a property_3
match was found.
I think I can do it with lots of SELECT/FROM, but it seems too complicated to me.
I tried to use CASE WHEN ___ LIKE ___ THEN ___ END
but I couldn’t succeed. In this case I get cells with null after grouping:
SELECT id,
CASE WHEN meta_data.key LIKE 'property_1' THEN meta_data.value END AS property_1,
CASE WHEN meta_data.key LIKE 'property_2' THEN meta_data.value END AS property_2,
CASE WHEN meta_data.key LIKE 'property_3' THEN meta_data.value END AS property_3
FROM meta_data
2
Answers
I would guess:
This an optimized way to do it using
GROUP BY
with the aggregate functionMAX()
:Demo here