0

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:

  1. Filter rows that have a parent_field_id value of either 4 or 5
  2. Out of those rows, I want to join all those that share the same parent_entry_id.
  3. Return the parent_entry_id as event_data_id.
  4. Return the child_entry_id as a user_id if parent_field_id of the same row is 5.
  5. Return the child_entry_id as a event_id if parent_field_id of the same row is 4.

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.

4

1 回答 1

1

接近了:

SELECT t1.`parent_entry_id` AS event_data_id,
       t1.`child_entry_id` AS user_id,
       t2.`child_entry_id` AS event_id
FROM `exp_playa_relationships` AS t1
INNER JOIN `exp_playa_relationships` AS t2
        ON t2.`parent_entry_id` = t1.`parent_entry_id`
           AND t2.`parent_field_id` = 4
WHERE  t1.`parent_field_id` = 5

具体来说,您必须告诉它从哪个行集中提取相关数据。

顺便说一句,您当前的数据库设计会让您更加头疼……我建议将信息提取到“结果”表中(除非这是为了什么?)。

于 2013-03-14T23:34:28.613 回答