我有我的产品表的结果集,同时尝试在最后两列中返回正确的结果,similar_sku_exists和similar_sku_in_stock。
目标是首先确定表中是否存在类似的sku并返回yes / no。
第二个确定其中一个类似的skus是否有库存并返回该sku名称。
类似的sku由相同的sku名称+等级的第一个字母定义。 例如," ABC-11-A"的所有实例将是相似的,因为他们具有相同的新条件。同样地" ABC-11-B"将是相似的,因为他们都是翻新条件。
id sku condition grade stock similar_sku_exists similar_sku_in_stock
1 ABC-11-A1 new A1 0 yes ABC-11-A2
2 ABC-11-A2 new A2 10 yes
3 ABC-11-B1 refurb B1 10 yes
4 ABC-11-B2 refurb B2 0 yes ABC-11-B1|ABC-11-B2-LP
5 ABC-11-B2-LP refurb B2-LP 10 yes
6 DEF-2-F-A1 new A1 0 no
7 DEF-2-G-B1 refurb B1 10 yes
8 DEF-2-G-B2 refurb B2 0 yes DEF-2-G-B1
到目前为止,我有这个查询但是dosn似乎没有返回正确的结果
select
id,
sku,
`condition`,
grade,
stock,
case when left(p.sku, length(p.sku)-length(p.grade)+1)
in (select left(p.sku, length(p.sku)-length(p.grade)+1))
then 'yes' else 'no' end as similar_sku_exists,
if(p.stock = 0,
case when left(p.sku, length(p.sku)-length(p.grade)+1)
in (select left(p.sku, length(p.sku)-length(p.grade)+1) and p.stock >0
)
then group_concat(distinct(p.sku) separator '|')
else '' end,'') as similar_sku_in_stock
from products as p
非常感谢任何选择
答案 0 :(得分:0)
这是一种获得类似skus库存的方法:
select p.*,
(select group_concat(p2.sku)
from products p2
where substring_index(p2.sku, '-', 1) = substring_index(p.sku, '-', 1) and
left(subsctring_index(p2.sku, '-', -1), 1) = left(substring_index(p.sku, '-', -1), 1) and
p2.sku <> p.sku and
stock > 0
) similar_skus_in_stock
from products p;
可以使用类似的查询来确定是否存在类似的skus。