我目前在MySQL表中有大约1,000种产品,每种产品似乎都是重复的(1个产品SKU,1个产品MPN或制造商产品编号),如下所示:
+--------------+------------+----------------+-----------------+------------------------+
| V_Article_ID | Article_ID | V_Article_Code | Brand_Domain_ID | Prefered_V_Article_ID |
+--------------+------------+----------------+-----------------+------------------------+
| 11003 | 7043 | AA4011 | null | 11002 |
| 11002 | 7043 | U-30G-BK | 101036 | null |
+--------------+------------+----------------+-----------------+------------------------+
理想情况下,我希望将两行合并为一行用于EACH产品(正如您可以看到两行中的article_id相同),保持Brand_Domain_ID为NOT NULL并拆分两个独立的Vendor_Article_Code&#39 ; s分为两个单独的列; SKU(AA4011)和MPN(U-30G-BK),因此输出看起来像这样:
+------------+--------+----------+-----------------+
| Article_ID | SKU | MPN | Brand_Domain_ID |
+------------+--------+----------+-----------------+
| 7043 | AA4011 | U-30G-BK | 101036 |
+------------+--------+----------+-----------------+
我目前正在使用以下语句来实现我想要的(如果只针对基于Article_ID的单个产品):
SELECT article_id,
case WHEN v_article_code REGEXP '^AA' THEN v_article_code END as SKU,
case WHEN v_article_code NOT REGEXP '^AA' THEN v_article_code END as MPN,
Brand_Domain_ID
FROM vendor_article
WHERE article_id = 7043
+------------+--------+----------+-----------------+
| Article_ID | SKU | MPN | Brand_Domain_ID |
+------------+--------+----------+-----------------+
| 7043 | null | U-30G-BK | null |
+------------+--------+----------+-----------------+
| 7043 | AA4011 | null | 101036 |
+------------+--------+----------+-----------------+
我的问题是:有没有办法将其减少,以便两行成为一行,没有空元素和相同的Article_ID?此外,是否有一种快速方法可以遍历每个Article_ID,例如PHP中的for循环?我知道如何将输出插入到新表中,我只是不确定解决方案的最佳方法。
非常感谢任何帮助。
答案 0 :(得分:1)
您需要将表格加入自身,如下所示:
select sku.article_id as Article_Id,
sku.v_article_code as SKU,
mpn.v_article_code as MPN,
coalesce(sku.brand_domain_id,mpn.brand_domain_id) as Brand_Domain_Id
from vender_article sku join vender_article mpn
on sku.article_id = mpn.article_id
where sku.v_article_code like 'AA%'
and mpn.v_article_code not like 'AA%';
编辑:有v_article_id,我应该有v_article_code。
答案 1 :(得分:1)
又一个实施:
select a.article_id, a.v_article_code MKU, b.v_article_code MPN,
ifnull(a.brand_domain_id, b.brand_domain_id) brand_domain_id,
ifnull(c.channel_sku, d.channel_sku) channel_sku
from vendor_article a
join vendor_article b on a.article_id = b.article_id
and a.brand_domain_id is not null and b.prefered_v_article_id is not null
left join vendor_article_channel c on a.v_article_id = c.vendor_article_id
left join vendor_article_channel d on b.v_article_id = d.vendor_article_id;