我有mysql表的产品。其中有字段名称,如id,name,sku,program,buyurl等。现在我想找到基于sku但具有不同程序名称的重复记录。我实际上是为了价格比较功能。 这是我的代码,用于查找重复记录,这很好但我的问题是它有相同的程序名称,我需要它用于不同的。
SELECT id, name, products.sku FROM products
INNER JOIN (SELECT sku FROM products
GROUP BY sku HAVING count(sku) > 1) dup ON products.sku= dup.sku
示例数据:
id | name | sku | programme | buyurl 1 | pro1 | 123 | KFC | kfc.com 2 | pro2 | 123 | McDonald | mcdonald.com 3 | pro3 | 456 | McDonal | mcdonald.com 4 | pro4 | 123 | KFC | kfc.com
必需的输出应为
id | name | sku | programme | buyurl 1 | pro1 | 123 | KFC | kfc.com 2 | pro2 | 123 | McDonald | mcdonald.com
由于sku
相同且programme
不同。
任何帮助将不胜感激。
答案 0 :(得分:3)
如果我理解正确,这个查询对您有用:
SELECT p1.id, p1.name, p1.sku, p1.programme
FROM product p1 JOIN product p2
ON p1.sku = p2.sku AND p1. programme <> p2.programme
如果没有,请添加一些样本数据和预期结果。
根据示例数据,尝试此查询:
SELECT * FROM product
WHERE id IN(
SELECT p1.id
FROM (SELECT MIN(id) as id, sku, programme FROM product GROUP BY sku, programme) p1
JOIN (SELECT MIN(id) as id, sku, programme FROM product GROUP BY sku, programme) p2
ON p1.sku = p2.sku AND p1.programme <> p2.programme
)
答案 1 :(得分:2)
你可以尝试
SELECT p.id, name, sku, programme, buyurl
FROM
(
SELECT MIN(t1.id) id
FROM products t1 JOIN products t2
ON t1.sku = t2.sku
AND t1.programme <> t2.programme
GROUP BY t1.sku, t1.programme
) q JOIN products p
ON q.id = p.id
输出:
| ID | NAME | SKU | PROGRAMME | BUYURL | |----|------|-----|-----------|--------------| | 1 | pro1 | 123 | KFC | kfc.com | | 2 | pro2 | 123 | McDonald | mcdonald.com |
这是 SQLFiddle 演示