我正在尝试开发一个计算产品尺寸的报表,并根据该计数的数量插入一个报表。
例如,
我有一件衬衫,有 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 语句对此更有效,但我都不知道。
最佳答案
如果您使用的是 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
但是,也许您不需要 Table2 中的数字是连续的。也许没关系,只要它们的顺序正确(所以菜单中 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
关于mysql - 创建根据 MYSQL 中的计数插入的条件 SQL 选择语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53215395/