创建一个条件SQL选择语句,该语句根据MYSQL中的计数插入

时间:2018-11-08 20:09:16

标签: mysql sql if-statement insert case

我正在尝试开发一种对产品尺寸进行计数的语句,并根据该计数值插入一条语句。

例如,

我有一件衬衫,它有3种尺寸(S,M,L)。要达到伸手可及的距离,我需要插入一条SQL语句。 insert语句将在表2上插入菜单位置。

表1

ID |  Product | Size
1      Shirt      S  
2      Shirt      M
3      Shirt      L

表2

ID  |  Dropdown_menu_Position
1        0
2        1
3        2

我知道以下查询不正确,但是我正在努力解决其背后的逻辑。任何SQL专家都可以帮助解决或指导我正确的方向吗?

INSERT INTO Table2
CASE
WHEN COUNT (SIZE) = 1 THEN
     SELECT NULL, '0' 
WHEN COUNT (SIZE) = 2 THEN
     SELECT NULL, '1' 
WHEN COUNT (SIZE) = 3 THEN
     SELECT NULL, '2' 
ELSE ''
END

我不擅长CASE语句,也许IF语句对此效果更好,但是我都不知道。

1 个答案:

答案 0 :(得分:0)

如果您使用的是MySQL 8.0,则可以使用窗口功能。它们可用于基于组生成编号:

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

在早期版本的MySQL中,这些功能不存在,因此无法使用。但是,对于这种特殊情况,您确实应该能够使用count来检查当前行之前有多少行。如果您有一个单独的表来查询尺寸,则此查询非常容易阅读,但如果没有,则必须在查询中两次嵌入查找表。下面的示例假定了一个单独的表:

-- 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

但是,也许您不需要表2中的数字是连续的。只要它们的顺序正确(也许M在菜单中的S之下),也许就可以了。当然,这取决于您的代码,但是如果可能的话,您可以简单地编写以下代码:

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