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 sdfs@ya.ru
2 gdgd@ya.ru
3 ffdg@ya.ru
4 fgdfgdf@ya.ru
5 gfg@ya.ru
6 dffet@ya.ru
7 gfg@ya.ru
8 gfg@ya.ru
9 hjg@ya.ru
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" "sdfs@ya.ru"
The procedure must get an input parameter (for example "cat") and:
- find the line where
property_3is equal to the inputparameterand get the id from this row (for example "1"), - select the fields, that I need, from the
meta_datatable, where theidis equal to ouridfrom the first point (for exampleproperty_1,property_2,property_3), - then rotate them from rows to columns,
- and finally add
emailfromusertable 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
>Solution :
I would guess:
SELECT
id,
meta_data1.value AS property_1,
meta_data2.value AS property_2,
meta_data3.value AS property_3,
email
FROM
meta_data AS meta_data1,
meta_data AS meta_data2,
meta_data AS meta_data3,
users
WHERE
meta_data1.id = users.id AND
meta_data2.id = users.id AND
meta_data3.id = users.id AND
meta_data1.key = "property_1" AND
meta_data2.key = "property_2" AND
meta_data3.key = "property_3"


