0

I want to create a combination of items from different categories ids.

Can you help me?

table

+---------+-------------+------------+
| post_id | category_id | post_title |
+---------+-------------+------------+
| 1       | 1           | Red        |
| 2       | 1           | Black      |
| 3       | 2           | Medium     |
| 4       | 3           | Male       |
| 5       | 3           | Female     |
+---------+-------------+------------+

The query results I want is as follows:

Red-Medium-Male
Black-Medium-Male
Red-Medium-Female
Black-Medium-Female

For example, if there were items belonging to 6 different categories, it would be like below:

Red-Medium-Male-Other1-Other2-Other3
Mert Aşan
  • 366
  • 1
  • 6
  • 18

1 Answers1

1

You can use a cross join and filtering:

select t1.post_title, t2.post_title, t3.post_title
from t t1 cross join
     t t2 cross join
     t t3
where t1.category_id = 1 and
      t2.category_id = 2 and
      t3.category_id = 3;

You can generalize this using a recursive CTE:

with recursive tt as (
      select t.*, dense_rank() over (order by category_id) as cat_seqnum
      from t
     ),
     cte as (
      select cat_seqnum, post_title
      from tt
      where cat_seqnum = 1
      union all
      select  tt.cat_seqnum, concat_ws('-', cte.post_title, tt.post_title)
      from cte join
           tt
           on tt.cat_seqnum = cte.cat_seqnum + 1
     )
select *
from cte
where cat_seqnum = (select max(cat_seqnum) from tt);

Here is a db<>fiddle.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • Thanks for your answer. But the count of categories is unclear. There should be something like a loop in the query. If you want to get an idea of what I want to do: https://stackoverflow.com/q/64837507/6320082 – Mert Aşan Nov 16 '20 at 02:01
  • 1
    @MertA. . . . That actually makes the question much more interesting. – Gordon Linoff Nov 16 '20 at 02:12
  • The question in the url was very complex. At least I created a simpler question to create the combination. Nobody answered the topic in the url. and my english was insufficient. – Mert Aşan Nov 16 '20 at 02:29
  • Thank you very much for your answer. Looks fine. I have a little problem :) The version of both the server and MAMP is mysql 5.7.26. Is it possible to do this with Mysql 5.7.26? – Mert Aşan Nov 16 '20 at 02:29
  • 1
    @MertA . . . You cannot do it with a single query in pre-8.0. You would need a stored procedure or other looping mechanism. – Gordon Linoff Nov 16 '20 at 02:33