MySQL query help

I am trying to construct a MySQL query and I have found that it is impossible to express the entire problem conversationally so that I can get help online. Therefore, I am breaking the query down into its simplest parts and I am going to attempt to get help on the problem points one at a time. The database has too many fields to be replicated here for reference so I’m hoping simple queries will make the issue clear.

Currently I’m joining on a junction table where there are 7 possible category selections. Each item is related to two and only two of the 7 category options. I want to query the items and include in the results two columns cat1 and cat2. The following is the query I am using:

SELECT exp_weblog_data.entry_id,
CASE WHEN exp_category_posts.cat_id = '15' OR exp_category_posts.cat_id = '16' THEN exp_category_posts.cat_id END as cat1,
CASE WHEN exp_category_posts.cat_id = '17' OR exp_category_posts.cat_id = '20' OR exp_category_posts.cat_id = '19' OR exp_category_posts.cat_id = '22' OR exp_category_posts.cat_id = '18' THEN exp_category_posts.cat_id END as cat2
FROM exp_weblog_data
INNER JOIN exp_category_posts
ON exp_weblog_data.entry_id = exp_category_posts.entry_id
WHERE exp_weblog_data.entry_id = 3013

Results
entry_id cat1 cat2
3013 16 NULL
3013 NULL 22

As you can see, since there are 2 values in the junction table, I get 2 records returned. I want just one record returned with the values for cat1 and cat2 assigned to that record. Grouping the results by adding

GROUP BY exp_weblog_data.entry_id;

Results
entry_id cat1 cat2
3013 16 NULL

results in one record, but a lost cat2 value. How do I structure this query so I get one result with both cats intact?

You need to aggregate the data.

select exp_weblog_data.entry_id,
       max(case when exp_category_posts.cat_id in (15,16) then exp_category_posts.cat_id end) as cat1,
       max(case when exp_category_posts.cat_id in (17,20,19,22,18) then exp_category_posts.cat_id end) as cat2
  from exp_weblog_data
  join exp_category_posts
    on exp_weblog_data.entry_id = exp_category_posts.entry_id
 where exp_weblog_data.entry_id = 3013
 group
    by exp_weblog_data.entry_id
1 Like

That works, thanks!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.