I'm trying to write a SQL query that looks at a single MySQL DB table (exp_playa_relationships
) which stores relationship data of CMS' posts and which data structure looks like this:
rel_id | parent_entry_id | parent_field_id | child_entry_id
-----------------------------------------------------------------
55 | 3 | 2 | 1
56 | 3 | 2 | 4
58 | 1 | 2 | 4
59 | 8 | 4 | 2
60 | 8 | 5 | 1
63 | 4 | 2 | 3
64 | 9 | 4 | 6
65 | 9 | 5 | 3
rel_id
is unique, other columns are not.
I would like to generate the following out of the data above:
event_data_id | user_id | event_id
--------------------------------------
8 | 1 | 2
9 | 3 | 6
The parent_field_id
value itself is discarded in the final output but is needed to figure out if the row's child_entry_id
signifies a user_id
or event_id
.
parent_entry_id
is the event_data_id
.
So in plain english I would like to:
- Filter rows that have a
parent_field_id
value of either4
or5
- Out of those rows, I want to join all those that share the same
parent_entry_id
. - Return the
parent_entry_id
asevent_data_id
. - Return the
child_entry_id
as auser_id
ifparent_field_id
of the same row is5
. - Return the
child_entry_id
as aevent_id
ifparent_field_id
of the same row is4
.
My current SQL query (not working) is this:
SELECT
t1.`parent_entry_id` AS event_data_id,
t1.`child_entry_id` AS user_id,
t1.`child_entry_id` AS event_id
FROM `exp_playa_relationships` AS t1
INNER JOIN `exp_playa_relationships` AS t2
ON t1.`parent_entry_id` = t2.`parent_entry_id`
WHERE t1.`parent_field_id` = 4 OR t1.`parent_field_id` = 5
What I cannot figure out specifically is how to avoid creating duplicates on the parent_entry_id
(SQL creates 2 new rows per row) and how to return child_entry_id
as either user_id
or event_id
based on the parent_field_id
value.
Any ideas would be much appreciated.