IF you are using MySQL 8.0, you can use window functions for this. They can be used to generate a numbering based on a group:
insert into Table2(Id, Dropdown_menu_Position)
select
t.ID,
--t.Product,
--t.Size,
ROW_NUMBER() over (
order by s.SortOrder
) partition by (t.Product) as Dropdown_menu_Position
from
Table1 t
inner join (
-- Inlined now, but maybe you can make a lookup table for this
select 'XS' as Size, 0 as SortOrder
union all select 'S', 1
union all select 'M', 2
union all select 'L', 3
union all select 'XL', 4
union all select 'XXL', 5
) s on s.Size = t.Size
In earlier versions of MySQL, these functions don't exist, and this won't work. However, for this particular case, you should indeed be able to use count
to check how many rows there are before the current one. If you have a separate table for the sizes, this query is quite readable, but if not, you would have to embed the lookup table twice in the query. The sample below assumed a separate table:
-- Assuming a lookup table like this:
create table Sizes as
select 'XS' as Size, 0 as SortOrder
union all select 'S', 1
union all select 'M', 2
union all select 'L', 3
union all select 'XL', 4
union all select 'XXL', 5;
-- Select all IDs and how often a smaller size exists for that product
insert into Table2(Id, Dropdown_menu_Position)
select
t.ID,
( select count(*)
from
Table1 t2
inner join Sizes s2 on s2.Size = t2.Size
where
t2.Product = t.Product and
s2.SortOrder < s.SortOrder) as Dropdown_menu_Position
from
Table1 t
inner join Sizes s on s on s.Size = t.Size
But, maybe you don't need the numbers in Table2 to be consecutive. Maybe it's okay, as long as they have the right order (so M is below S in the menu). This will, of course, depend on your code, but if that is possible, you can simply write this:
insert into Table2(Id, Dropdown_menu_Position)
select
t.ID,
s.SortOrder
from
Table1 t
inner join (
-- Inlined now, but maybe you can make a lookup table for this
select 'XS' as Size, 0 as SortOrder
union all select 'S', 1
union all select 'M', 2
union all select 'L', 3
union all select 'XL', 4
union all select 'XXL', 5
) s on s.Size = t.Size